如何下载在 Streamlit 应用程序中生成的 matplotlib 图形

How to download matplotlib graphs generated in a Streamlit app

有什么方法可以让用户在 Streamlit 应用程序中下载使用 matplotlib/seaborn 制作的图表吗?我设法获得了一个下载按钮,可以将数据框下载为 csv,但我不知道如何让用户下载图表。我在图表代码下方提供了代码片段。

感谢您的帮助!

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)

两种方法首先将图像保存到文件并提供下载,然后将图像保存到内存(磁盘上没有杂乱)并提供下载。

第一

"""
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"
    )

第二
先保存到内存。

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"
)

下载文件输出