Streamlit中Matplotlib绘图无输出:是否需替换plt.show()?
解决方案
是的,你需要替换plt.show(),Streamlit有专门的方法来渲染matplotlib图表,具体修改如下:
- 先确保导入Streamlit库:
import streamlit as st
- 将代码中的
plt.show()替换为st.pyplot(plt)
修改后的完整代码示例:
import matplotlib.pyplot as plt import streamlit as st def month_year(d): m, y = d months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] return months[m - 1] + '-' + str(y % 100) # 确保绘图代码不在函数缩进内 ax2 = new_df['Average_Answer_Speed'].plot(kind='bar', stacked=True, figsize=(15,10)) plt.xticks(rotation = 45) ax2.set_title('Average Call Answer Speed in Seconds', fontsize = 18, fontweight = "bold") ax2.set_xlabel('') for p in ax2.patches: ax2.annotate(f'{int(round(p.get_height()))}', (p.get_x() + p.get_width() / 2., p.get_height() / 2), ha='center', va='center', xytext=(0, 10), textcoords='offset points', color='white') # 替换plt.show() st.pyplot(plt)
补充说明:
- Streamlit的
st.pyplot()会接收matplotlib的当前figure对象(直接传plt即可),并在页面上渲染图表 - 注意原代码中绘图部分的缩进错误,要确保它不在
month_year函数内部,否则不会被执行
内容的提问来源于stack exchange,提问作者Ralph
相关产品推荐
相关产品推荐

