Is there any way to allow users to download a graph made using matplotlib/seaborn in a Streamlit app? I managed to get a download button working to download a dataframe as a csv, but I can't figure out how to allow users to download a graph. I have provided a code snippet below of the graph code.
Thank you for your help!
fig_RFC_scatter, ax = plt.subplots(1,1, figsize = (5,4))
ax = sns.scatterplot(data = RFC_results_df_subset, x = X_Element_RM, y = Y_Element_RM, hue = "F_sil_remaining", edgecolor = "k", legend = "full")
ax = sns.scatterplot(data = RFC_results_df_subset, x = X_Element_CM, y = Y_Element_CM, hue = "F_sil_remaining", edgecolor = "k", legend = None, marker = "s")
ax = plt.xlabel(X_Element_RM)
ax = plt.ylabel(Y_Element_RM)
ax = plt.xlim(x_min, x_max)
ax = plt.ylim(y_min, y_max)
ax = plt.xscale(x_scale)
ax = plt.yscale(y_scale)
ax = plt.axhline(y = 1, color = "grey", linewidth = 0.5, linestyle = "--")
ax = plt.axvline(x = 1, color = "grey", linewidth = 0.5, linestyle = "--")
ax = plt.legend(bbox_to_anchor = (1, 0.87), frameon = False, title = "% Sil. Remaining")
st.write(fig_RFC_scatter)
CodePudding user response:
Two approaches first save the image to file and offer for download and second save image to memory (no clutter on disk) and offer for download.
First
"""
Ref: https://docs.streamlit.io/library/api-reference/widgets/st.download_button
"""
import io
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
X = [1, 2, 3, 4, 5, 6, 7, 8]
Y = [1500, 1550, 1600, 1640, 1680, 1700, 1760, 1800]
sns.scatterplot(x=X, y=Y)
# Save to file first or an image file has already existed.
fn = 'scatter.png'
plt.savefig(fn)
with open(fn, "rb") as img:
btn = st.download_button(
label="Download image",
data=img,
file_name=fn,
mime="image/png"
)
Second
Save to memory first.
fn = 'scatter.png'
img = io.BytesIO()
plt.savefig(img, format='png')
btn = st.download_button(
label="Download image",
data=img,
file_name=fn,
mime="image/png"
)