Download Plotly plot as html

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! :slight_smile:

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! :partying_face:

6 Likes