You need to enable JavaScript to run this app. Matplotlib绘制堆叠柱状图仅显示其中一个绘图的问题如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制堆叠柱状图仅显示其中一个绘图的问题如何解决

问题原因

  • 数值量级不匹配:ontimepct是占比,数值区间为0~1,flights是航班数,数值在几百到一万区间,二者共用同一个Y轴时,占比的柱子高度远低于航班数柱子,几乎贴在X轴上,视觉上像没有显示。
  • 绘图逻辑不符合堆叠柱状图要求:当前代码的写法是簇状柱状图的逻辑(X轴偏移一个柱宽并列展示),堆叠柱状图需要给第二层柱子指定bottom参数,将第一层柱子的高度作为底部起点。
  • 语法小错误:plt.show后缺少调用括号(),部分运行环境下不会主动渲染图形。

修正方案

方案1:双Y轴展示两个不同维度的指标(更合理,两个指标维度不同,堆叠无实际业务意义)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = {'a':['Usair', 'delta', 'american', 'airlondon', 'United','Peoples Express','Joes airline and grill'],
        'b':[9052, 9394, 9837, 8911, 10251, 8092, 512],
        'c' :[3002,8000,7600,7933, 8123, 2089,109 ]
       }

df= pd.DataFrame(data)
df.columns = ['airline', 'flights', 'on time']
df['ontimepct'] = df['on time'] /df['flights']

ind = np.arange(7)
w = 0.35

fig, ax1 = plt.subplots()
# 第一个Y轴展示准点率
ax1.bar(ind - w/2, df['ontimepct'], w, color = 'r', label= 'On Time Rate')
ax1.set_ylabel('On Time Rate', color='r')
ax1.tick_params(axis='y', labelcolor='r')
ax1.set_xticks(ind)
ax1.set_xticklabels(df['airline'], rotation=45)

# 第二个Y轴展示航班总数
ax2 = ax1.twinx()
ax2.bar(ind + w/2, df['flights'], w, color = 'g', label='Total Flights')
ax2.set_ylabel('Total Flights', color='g')
ax2.tick_params(axis='y', labelcolor='g')

# 合并图例
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')

plt.tight_layout()
plt.show()

方案2:堆叠柱状图实现(仅做语法演示,该业务场景下堆叠无实际参考价值)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = {'a':['Usair', 'delta', 'american', 'airlondon', 'United','Peoples Express','Joes airline and grill'],
        'b':[9052, 9394, 9837, 8911, 10251, 8092, 512],
        'c' :[3002,8000,7600,7933, 8123, 2089,109 ]
       }

df= pd.DataFrame(data)
df.columns = ['airline', 'flights', 'on time']
df['ontimepct'] = df['on time'] /df['flights']

ind = np.arange(7)
w = 0.5

# 第一层柱子
plt.bar(ind, df['flights'], w, color = 'g', label='Total Flights')
# 第二层柱子指定bottom为第一层的高度,实现堆叠
plt.bar(ind, df['ontimepct'], w, bottom=df['flights'], color = 'r', label= 'On Time Rate')

plt.xticks(ind, df['airline'], rotation=45)
plt.legend()
plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Mike Feldman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 21:45:07