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

Python使用matplotlib绘制并列堆叠柱状图仅显示第二个图问题求助

问题原因

pandas的DataFrame.plot()方法默认会自动创建独立的绘图坐标轴对象,不会主动复用你通过plt.subplot()提前声明的子图位置,因此第一个子图声明后,health_sex1.plot()自行创建了新窗口绘图,第二个子图声明后才刚好对应上绘图位置,就出现了只有第二个子图生效、额外弹出空白窗口的问题。

修正后的代码
import matplotlib.pyplot as plt

# 提前创建1行2列的子图,拿到两个坐标轴对象ax1、ax2,可自行调整figsize参数修改画布大小
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))

# 第一个堆叠柱状图指定绘制在ax1上
health_sex1.plot(kind = 'bar', stacked = True, ax=ax1)
ax1.set_title("Health with Sex Overlay")
ax1.set_xlabel("Health")
ax1.set_ylabel("Count")

# 第二个堆叠柱状图指定绘制在ax2上
health_educ1.plot(kind = 'bar', stacked = True, ax=ax2)
ax2.set_title("Health with Education Overlay")
ax2.set_xlabel("Health")
ax2.set_ylabel("Count")

# 自动调整子图间距,避免标签、标题重叠
plt.tight_layout()
plt.show()
核心调整点
  • 调用plt.subplots()提前一次性创建所有子图的坐标轴对象,避免和pandas自动创建的坐标轴冲突
  • 每个DataFrame.plot()调用时传入ax参数,指定绘图的目标坐标轴
  • 补充plt.tight_layout()自动调整布局,避免子图元素重叠

内容的提问来源于stack exchange,提问作者Learning and Improving

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:54:04