Save matplotlib plot obtained from a function


I want to download an image that is generated with matplotlib pyplot. I have tested different solutions but they are not working in my case. In this case, I have a function which is assembling a plot and then I want to save this figure. I am using streamlit in the cloud (with github)

Steps to reproduce

Code snippet:

#code inspired from:

#this function takes a list of images and captions (optionally)
#it should plot the figure
def download_images(images, captions, cols = 2, rows = 2):
    n_img = len(images)
    figure, axis = plt.subplots(rows, cols)
    ax = axis.flatten()
    for i in range(n_img):
      if captions is not None:

#here I create a button to decide if you want to save the images
#it should then execute the function above and save in png
save_all_imgs = st.button('save all images',
                                    key = '1')
            if save_all_imgs:
                                captions= None, 
                                cols = 3, rows = 3 )
                plt.savefig(img, format='png')
                fn = 'scatter.png'
                img = io.BytesIO()
                btn = st.download_button(
                label="Download image",

Expected behavior:

it should save/download the image

Actual behavior:

there is no error, the function is executed but then no image is downloaded.

Debug info

I am using streamlit in the cloud

Requirements file


Thank you very much for your help

Hi @Salvo,

Does this functionality work when you run the app locally?

1 Like

The matplotilib function is working on Google Colab (I use for the GPU), I have actually tested different things. The streamlit app is on the cloud (I use GitHub and then the cloud provided by streamlit)

This function is simply assembling some images obtained before in a unique plot with the corresponding captions. The idea is in the app I am generating some PIL images and then I want to assembly with matplotlib, I want to use a function because I am using the same idea different times in the app (the function takes an arbitrary number of images and captions). I can download the single images (which it works) but the issue arise when I try to do that with a function and matplotlib.

Moreover, it is not returning an error (I checked the log), it simply does not download anything

thank you for your help