Using pyplot and pandas to display a horizontal stacked bar plot

At the moment I have:

fig, ax = plt.subplots()
ax = df.plot.barh(stacked=True)
st.pyplot(fig)

The dataframe for reference if necessary looks like:

       A     B     C     D      E
Cat1  5.3   NaN   NaN   NaN    NaN
Cat2  NaN   NaN   12.1  NaN    NaN
Cat3  NaN   NaN   NaN   3.4    4.5
Cat4  NaN   2.8   NaN   NaN    NaN                                       

where if I get rid of the ‘fig’ in st.pyplot(fig), forcing the function to render the global figure - it produces a nice stacked bar plot, but with the deprecation warning.

So I know it’s not a problem with matplotlib producing the plot from my dataframe, but actually with streamlit displaying the plot.

Basically, what matplotlib syntax do I need to get streamlit to produce this horizontal stacked bar plot?

Thanks in advance

Hi @bemortz, welcome to the Streamlit community! :wave: :partying_face:

st.pyplot expects a Matplotlib Figure object. That object can be accessed by adding a .figure attribute to df.plot.barh(stacked=True):

import pandas as pd
import streamlit as st

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ["snail", "pig", "elephant", "rabbit", "giraffe", "coyote", "horse"]
df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index)

st.pyplot(df.plot.barh(stacked=True).figure)

1 Like