Reputation: 1
I am trying to export my plotly graph object to a png in my Streamlit app, I am running my Streamlit app locally using: python -m streamlit run Streamlit_Mapping.py
The code I am referring to looks like this:
import plotly.graph_objects as go
import plotly.io as pio
import streamlit as st
def main():
fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[3, 2, 1], mode='markers'))
filename = 'image.png'
with st.spinner('exporting image'):
try:
pio.write_image(fig, filename, format="png", engine="kaleido")
print("Image export successful.")
except Exception as e:
print(f"Image export failed: {e}")
with open(filename, "rb") as file:
st.download_button(
label="Download Plot as PNG",
data=file,
file_name=filename,
mime="image/png"
)
if __name__ == '__main__':
main()
My app gets stuck in the write_image function. When I run the code below which is not part of a streamlit app, it runs perfectly fine.
import plotly.graph_objects as go
from plotly.io import to_image
# Test Plotly GO image export locally
fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[3, 2, 1], mode='markers'))
try:
img = to_image(fig, format="png")
print("Image export successful.")
except Exception as e:
print(f"Image export failed: {e}")
I have tried python 3.11 and 3.9 with plotly 6.0.0, kaleido 0.4.1 and plotly 5.5.0 and kaleido 0.2.1 respectivley
I have tried the fix here: Saving a plotly image not working with kaleido even though it is installed
And the fix here: https://github.com/plotly/Kaleido/issues/61
Without any luck...
Does anyone know how to tackle this issue?
Upvotes: 0
Views: 52
Reputation: 69388
I can't see any issue with your code, but if you think write_image
might be taking longer than expected, you can add some timeout
#! /usr/bin/env streamlit run
import plotly.graph_objects as go
import plotly.io as pio
import streamlit as st
import asyncio
async def write_image(pio, fig, filename):
pio.write_image(fig, filename, format="png", engine="kaleido")
async def main():
fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[3, 2, 1], mode='markers'))
filename = 'image.png'
with st.spinner('exporting image'):
try:
await asyncio.wait_for(write_image(pio, fig, filename), timeout=15)
st.success("Image export successful.")
except asyncio.TimeoutError:
st.error(f"Timed out")
except Exception as e:
st.error(f"Image export failed: {e}")
with open(filename, "rb") as file:
st.image(filename)
st.download_button(
label="Download Plot as PNG",
data=file,
file_name=filename,
mime="image/png"
)
if __name__ == '__main__':
asyncio.run(main())
Upvotes: 0