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.figure(figsize=(8,8))
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.legend()
plt.title(‘Customer Groups’)
plt.xlabel(‘Income’)
plt.ylabel(‘Spending Score’)
plt.show()

How should I display these plots in streamlit?
Thanks

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 plt.show()

or

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

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!
Fanilo

2 Likes

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

1 Like

Thank you. It worked!

I have a similar question but different as source library. How to display AutoViz graphs from python into streamlit App?
the following python lines will display many graphs that I need to show them in Streamlit:

from autoviz import AutoViz_Class
AV = AutoViz_Class()
dft = AV.AutoViz(“sample.csv”)

I used
%matplotlib inline
to see the graphs in notebook first