如何用Matplotlib语法让Streamlit显示Pandas DataFrame水平堆叠条形图?
解决Streamlit中Matplotlib水平堆叠条形图的显示问题
我用以下代码尝试在Streamlit中展示Pandas DataFrame的水平堆叠条形图:
fig, ax = plt.subplots() ax = df.plot.barh(stacked=True) st.pyplot(fig)
对应的DataFrame结构如下:
A B C D E Cat1 5.3 NaN NaN NaN NaN Cat2 NaN NaN 12.1 NaN NaN Cat3 NaN NaN NaN 3.4 4.5 Cat4 NaN 2.8 NaN NaN NaN
目前遇到的问题:调用st.pyplot(fig)无法正常显示图形,但去掉fig参数直接调用st.pyplot()(渲染全局图形)能生成正常的堆叠条形图,不过会触发弃用警告。已确认Matplotlib生成图形本身无问题,问题出在Streamlit的图形显示环节,需要合适的Matplotlib语法解决。
解决方案
问题根源在于df.plot.barh(stacked=True)默认会创建新的Axes对象,而非复用你提前创建的ax,导致fig中未包含实际绘图内容。可以通过以下两种方式解决:
指定Axes对象给Pandas绘图
把提前创建的ax传给plot方法,强制绘图在该Axes上进行,确保fig正确包含图形:fig, ax = plt.subplots() df.plot.barh(stacked=True, ax=ax) st.pyplot(fig)从Axes获取对应Figure对象
直接从Pandas绘图返回的Axes中提取其关联的Figure,再传给Streamlit:ax = df.plot.barh(stacked=True) st.pyplot(ax.figure)
这两种方式都能避免依赖全局图形,消除弃用警告,同时保证堆叠条形图正常显示。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

