A download button with custom CSS

Just a heads-up that might be interesting for some: With some little adjustment this download button can be used to download matplotlib figures as a .png file, too (see my use-case here: https://solar-mach.github.io)!

For that download_button() is defined as before in this thread. Then, the figure is created and shown in streamlit:

import io
import streamlit as st
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12, 8))
[...]
st.pyplot(fig)

Afterwards plt.savefig() is called (which unfortunately slows down the whole web-app by 1-2 seconds in loading) and handed over to download_button():

filename = 'some_name.png'
plot2 = io.BytesIO()
plt.savefig(plot2, format='png', bbox_inches="tight")
download_button_str = download_button(plot2.getvalue(), filename, f'Download figure as .png file', pickle_it=False)
st.markdown(download_button_str, unsafe_allow_html=True)

Would be really interested in feedback on this addition!

1 Like