Hello everyone. My matplotlib figure is too big, and I can’t change its size. I tried passing the figsize parameter both when creating the fig object and in the st.pyplot method. The figure size does not change.
Hi @Zylatis, I’m sorry to hear you’re having trouble with resizing matplotlib figures.
Could you share a working example or code a snippet where you are trying unsuccessfully to resize a figure? We could try figuring it out together.
In the meantime, I put together a minimal example based on a matplotlib tutorial. I vary the values of the width and height parameters in figsize using sliders:
Here is an example displaying a numpy array using st.image
import streamlit as st
import matplotlib
import numpy as np
def display_array(arr, colormap='viridis', width=None):
""" display a 2D array in streamlit with a color map"""
# color map
cm = matplotlib.cm.get_cmap(colormap)
# rgb visualization
rgb = cm(arr)
# display in app
st.image(rgb, width=width)
# numpy array
arr = np.random.rand(300,300)
# display numpy array in streamlit app
display_array(arr)
One thing to note is that even in @snehankekre 's excellent example showing matplotlib resizing in action, the final displayed width can’t be changed. The image always fills 100% of the width allotted in the column it lives in. Is there any way around that so that i.e. a 3-inch wide image is actually 3 inches wide instead of being widened to 100% after matplotlib’s rendering of the image?
Thanks for your patience! Here’s a workaround with 2 additional lines of code. Instead of using st.pyplot, you can convert the matplotlib.figure.Figure object into an image that’s held temporarily in memory, and then display it using st.image like so:
Awesome, thanks for the workaround! Is there a reason st.image respects the image width but st.pyplot doesn’t, or is that something I could submit an issue for? It would be nice to either have a width kwarg in st.pyplot just like st.image and/or change st.pyplot’s default behavior to not expand to 100% width, just like st.image
Is this workaround still supposed to work? It doesn’t work for me on Streamlit 1.11.
I am trying to display a figure object via st.pyplot or st.image within st.expander and the image always gets resized to the full width of the expander.
Edit: If I remove the expander the image is still exanded to the surrounding column width.
Edit 2: Also doesn’t work if I remove both the surrounding expander and the column.