I would like to allow the user to download a plotly plot as a .html
file. This is well supported by plotly. I can’t get it to work though. I am trying
from io import StringIO, BytesIO
import base64
import streamlit as st
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
st.plotly_chart(fig)
mybuff = StringIO()
fig.write_html(mybuff, include_plotlyjs='cdn')
mybuff = BytesIO(mybuff.read().encode('utf8'))
href = f'<a href="data:file/txt;base64, {base64.b64encode(mybuff.read())}" download="plot.html">Downlo\
ad plot</a>'
st.markdown(href, unsafe_allow_html=True)
I confirm that fig.write_html("myplot.html")
outputs the proper thing.
1 Like
Solved!
mybuff = StringIO()
fig.write_html(mybuff, include_plotlyjs='cdn')
mybuff = BytesIO(mybuff.getvalue().encode())
b64 = base64.b64encode(mybuff.read()).decode()
href = f'<a href="data:text/html;charset=utf-8;base64, {b64}" download="plot.html">Download plot</a>'
st.markdown(href, unsafe_allow_html=True)
and the user gets a portable self-contained plotly plot!
11 Likes
For people coming here in the future that want to use streamlit’s st.download_button:
buffer = io.StringIO()
fig.write_html(buffer, include_plotlyjs='cdn')
html_bytes = buffer.getvalue().encode()
st.download_button(
label='Download HTML',
data=html_bytes,
file_name='stuff.html',
mime='text/html'
)
4 Likes
Coming back to provide an updated answer? Not all heroes wear capes
7 Likes
Hi,
Is there any way to download multiple plotly plots as HTML, to zipping them and download it as .zip
Do you have any idea why from one point on the plot started to download in black and white, when the original is in color? Months ago there was no such problem.