Home > Enterprise >  Save plotly plots in a single pdf
Save plotly plots in a single pdf

Time:09-12

My code is generating poorly plots (around 100). This needs to be saved in a single pdf file.

for i in range(len(stats_ETF.columns)):
    fig2 = px.scatter(stats_ETF, x = 'Date', y = stats_ETF.columns[i 1])
    fig2.show()

fig 2 has each of those plots. Can someone help on how all plots can be saved in a single pdf?

CodePudding user response:

You can arrive at following solution using these articles/documentation:

You need to install: pip install kaleido

import pandas as pd
import plotly.express as px
import plotly.io as pio
from plotly.subplots import make_subplots
import plotly.graph_objects as go

stats_ETF = pd.DataFrame({
    "Date": ["2022-01-01", "2022-02-01", "2022-03-01", "2022-04-01", "2022-01-05"],
    "Earnings": [250, 220, 250, 230, 250],
    "Expenses": [200, 180, 210, 190, 220],
    "Earnings_1": [250, 220, 250, 230, 250],
    "Expenses_1": [200, 180, 210, 190, 220],
    "Earnings_2": [250, 220, 250, 230, 250],
    "Expenses_2": [200, 180, 210, 190, 220],
    "Earnings_3": [250, 220, 250, 230, 250],
    "Expenses_3": [200, 180, 210, 190, 220],
    "Earnings_4": [250, 220, 250, 230, 250],
    "Expenses_4": [200, 180, 210, 190, 220],
    })

fig = make_subplots(rows=len(stats_ETF.columns)-1, cols=1)

for i in range(1, len(stats_ETF.columns)):
    fig.add_trace(
        go.Scatter(x=stats_ETF["Date"], y=stats_ETF[stats_ETF.columns[i]]),
        row=i, col=1
    )    

fig.update_layout(height=200*len(stats_ETF.columns), width=800, title_text="Multiple Subplots")
# fig.show()
pio.write_image(fig, "stats_plots.pdf", format="pdf", engine="kaleido")

This generates a PDF with all plots in one page.

  • Related