'Save image with fig.write_image in Python Plotly
I would like to save images within plotly fig.write_image
using a forloop, where each image name include a customised 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 **
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 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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|