python-3.xmatplotlibplotstreamlit

Having Problem with Pyplot Feature on Streamlit


#pie chart
import pylab
df_count_percent = (df_count['count_of_purchase/campaign'] / df_count['count_of_purchase/campaign'].sum()) * 100
plot0 = df_count_percent.plot.pie(y='count_of_purchase/campaign', fontsize=17,autopct='%0.2f%%',pctdistance=1.2,
                                     labeldistance=None)

pylab.ylabel('')
pylab.xlabel('')

plt.title('Count of Purchase or Campaign as Percentage (Pie)', fontsize=19,fontweight="bold",pad=6)

plt.legend(loc='upper right', fontsize=9,prop={'size': 17}, bbox_to_anchor=(2,1))
plot0=plt.figure(figsize=(16, 16))
plt.show()

# Plot a bar chart
figure_0=df_count.plot.barh( y="count_of_purchase/campaign",
         color='green',fontsize=15,edgecolor="#111111")

plt.title('Count of Purchase or Campaign', fontsize=16,fontweight="bold",pad=12)
figure_0.set_xlabel('\nFrequency',fontsize=14,fontweight="bold")
figure_0=plt.figure()
plt.show()
# Plot a bar chart as percentage
df_count_percent = (df_count['count_of_purchase/campaign'] / df_count['count_of_purchase/campaign'].sum()) * 100
fig=df_count_percent.plot.barh( y="count_of_purchase/campaign",fontsize=15 ,color='red',edgecolor="#111111")

plt.title('Count of Purchase or Campaign as Percentage',fontsize=16,fontweight="bold",pad=12) 

fig.set_xlabel('\nPercentage',fontsize=14,fontweight="bold")
fig = plt.figure(figsize = (18, 18))
plt.show()

Hello friends, I'm trying to plot the above three graphs on streamlit (pie and bar graphs), but the pie graph and the y=count_of_purchase/campaign graph are blank. I tried this code for streamlit: st.pyplot(fig) How can I plot these truly on streamlit? What is the problem, I don't know? Normally, the code is working on spyder/jupyter but the problem is with the interface. I couldn't show it on streamlit. I am waiting for your helps...


Solution

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

    import pylab
    df_count_percent = (df_count['count_of_purchase/campaign'] / df_count['count_of_purchase/campaign'].sum()) * 100
    plot0 = df_count_percent.plot.pie(y='count_of_purchase/campaign', fontsize=17,figsize=(16, 16),autopct='%0.2f%%',pctdistance=1.2,
                                       labeldistance=None,stacked=True)
    
    pylab.ylabel('')
    pylab.xlabel('')
    
    plt.title('Count of Purchase or Campaign as Percentage (Pie)', fontsize=19,fontweight="bold",pad=6)
    
    plt.legend(loc='upper right', fontsize=9,prop={'size': 17}, bbox_to_anchor=(2,1))
      
    plot0=plot0.figure
    st.pyplot(plot0)