How to save and concatenate plotly express images in a loop?

Question:

I made a loop that creates different figures using plotly express. The problem is I do not know how to save those figures. I want to save them in every loop.

The code:

import plotly.express as px

for i in range(0, max(df['frame']), 30):
    df1 = df[df['frame'].between(i, i + 30)] 
    df2 = df[df['frame'].between(i - 30, i)]
    df3 = pd.concat([df1, df2[df2.id.isin(df1.id)]], axis=0)

    # Here creates the fig
    fig = px.line(df1, x='smooth_y', y='smooth_x', color='id') 

    # I do NOT want to show it, I want to save it!
    fig.show()
Asked By: JN1997

||

Answers:

You can simply create an empty list, then append your figures to it.

import plotly.express as px

res = []
for i in range(10):
  # Here, generate your dataframe df1
  fig = px.line(df1)
  res.append(fig)

Then access your figures this way :

res[0].show() # Shows first figure
res[1].show() # Shows second figure
Answered By: john_hatten2

To save the image, you use the write_image() method. Something like this:

fig.write_image("path/to/your/fig1.png")

Take a look at the official documentation.

Answered By: accdias
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.