How to display matplotlib graphs in streamlit application

Dear Community
I want to display the matplotlib plots or graphs which I built for K-Means Clustering in streamlit app. Plots are visible in python script in backend, but don’t know how to show them in streamlit.
Can somebody help?

Here is my code snippet for plots
import matplotlib.pyplot as plt
plt.scatter(X[Y==0,0], X[Y==0,1], s=100, c=‘green’, label=‘Cluster 1’)
plt.scatter(X[Y==1,0], X[Y==1,1], s=100, c=‘red’, label=‘Cluster 2’)
plt.scatter(X[Y==2,0], X[Y==2,1], s=100, c=‘yellow’, label=‘Cluster 3’)
plt.scatter(X[Y==3,0], X[Y==3,1], s=100, c=‘black’, label=‘Cluster 4’)
plt.scatter(X[Y==4,0], X[Y==4,1], s=100, c=‘blue’, label=‘Cluster 5’)
plt.title(‘Customer Groups’)
plt.ylabel(‘Spending Score’)

How should I display these plots in streamlit?

Hello @Priti_Asolkar ,

I’m in holidays so I haven’t tested it to ensure this works, but from memory:
If you want to stick to the imperative Matplotlib API, then you’ll need to retrieve the Figure from the global state:

st.pyplot(plt.gcf()) # instead of


import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8))
# ...
st.pyplot(fig) # instead of

You can find an explanation + why I prefer the Object-Oriented API on 4 ways to display Seaborn charts in Streamlit - YouTube

Hope this helps!

1 Like

Thanks dear!
This works for me, thank you
Enjoy your holiday!

1 Like

Thank you. It worked!