1

I would like to save images within plotly fig.write_image using a forloop, where each image name includes a customized id and Timestamp value with a string format, shown below:

fig.write_image(f"{row.id},{row.Timestamp}.png")

**The id is 01-1 and the Timestamp is 2011-10-06 08:29:40 in Timestamp format **

The complete code looks like this:

def draw(summary_df, data_df):

    for i, row in summary_df.iterrows():

        sub_df = data_df[(data_df.id== row.id) & (data_df.Timestamp >= row.start_time- datetime.timedelta(minutes=1)) & (data_df.Timestamp <= row.end_time +datetime.timedelta(minutes=1))]

        fig = go.Figure()
        
        fig.add_trace(go.Scatter(x=sub_df.Timestamp, y=sub_df.Data,
                            mode='lines+markers+text',
                            text = sub_df.Data,
                            textposition="top center",
                            textfont=dict(
                                family="arial",
                                size=10,
                                color="#6570f9") ))


        fig.add_shape(type='line',
                        x0=sub_df.Timestamp.iloc[0],
                        y0=48,
                        x1=sub_df.Timestamp.iloc[-1],
                        y1=48,
                        line=dict(color='Red',
                        # dash="dashdot",
                        ),
                        xref='x',
                        yref='y'
        )

                            
        fig.update_layout(
            title=f'{i}. {row.id}, {row.Timestamp}', 
            xaxis_title="Timestamp",
            yaxis_title="Measurement",
            legend_title="Data",
            font=dict(
                size=11
            )
        )


        fig.write_image(f"{row.id},{row.Timestamp}.png")
        fig.show()

However, it caught an error:

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-30-eb8687cd8f7a> in <module>

<ipython-input-28-750952f89e28> in draw(summary_df, data_df)

---> 83         fig.write_image(f"{row.id}{row.Timestamp}.png")
     84         fig.show()
     85 

c:\Python38\lib\site-packages\plotly\basedatatypes.py in write_image(self, *args, **kwargs)
   3556         import plotly.io as pio
   3557 
-> 3558         return pio.write_image(self, *args, **kwargs)
   3559 
   3560     # Static helpers

c:\Python38\lib\site-packages\plotly\io\_kaleido.py in write_image(fig, file, format, scale, width, height, validate, engine)
    256     # ---------
    257     if file_is_str:
--> 258         with open(file, "wb") as f:
    259             f.write(img_data)
    260     else:

OSError: [Errno 22] Invalid argument: '01-12011-10-06 08:29:40.png'

I also tried to convert Timestamp into string but no luck. Does the issue lie with the timestamp string format?

xxx
  • 1,153
  • 1
  • 11
  • 23
nilsinelabore
  • 4,143
  • 17
  • 65
  • 122
  • 2
    Perhaps the error is due to a violation of the filename rules. I was able to save the file correctly under. `fig.write_image(f"{row.id}-{row.Timestamp.strftime('%Y-%m-%d_%H_%M_%S')}.png")` – r-beginners May 13 '22 at 06:59
  • 1
    I second what @r-beginners said. I don't think you can have the `:` character in a filename. See the most upvoted comment on [this question](https://stackoverflow.com/questions/25584124/oserror-errno-22-invalid-argument-when-use-open-in-python) – Derek O May 13 '22 at 15:56
  • Hi @r-beginners, thanks for your help - it's working now! Could you please tell me where you found this information? I can't seem to find it in the plotly doc. Also feel free to add an answer so I could accept it :) – nilsinelabore May 14 '22 at 01:21
  • 1
    The issue in this question is not plotly related but about file name rules. It has already been answered [here](https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names), so I will refrain from answering it. – r-beginners May 14 '22 at 02:02

0 Answers0