You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit中Matplotlib绘图无输出:是否需替换plt.show()?

解决方案

是的,你需要替换plt.show(),Streamlit有专门的方法来渲染matplotlib图表,具体修改如下:

  1. 先确保导入Streamlit库:
import streamlit as st
  1. 将代码中的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:45:36