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

如何在pandas barh水平条形图中仅对指定列实现堆叠展示

解决方法

实现堆叠水平条形与非堆叠水平条形并排展示,只需复用同一个Axes绘图对象,调整条形位置避免重叠即可,完整可运行代码如下:

import pandas as pd
import matplotlib.pyplot as plt

# 原始数据
d = pd.DataFrame({'DC': {'col0': 257334.0,
  'col1': 0.0,
  'col2': 0.0,
  'col3': 186146.0,
  'col4': 0.0,
  'col5': 366431.0,
  'col6': 461.0,
  'col7': 0.0,
  'col8': 0.0},
 'DC - IDC': {'col0': 32665.0,
  'col1': 0.0,
  'col2': 156598.0,
  'col3': 0.0,
  'col4': 176170.0,
  'col5': 0.0,
  'col6': 0.0,
  'col7': 0.0,
  'col8': 0.0},
 'No Address': {'col0': 292442.0,
  'col1': 227.0,
  'col2': 298513.0,
  'col3': 117167.0,
  'col4': 249.0,
  'col5': 747753.0,
  'col6': 271976.0,
  'col7': 9640.0,
  'col8': 211410.0}})

# 配置条形参数
bar_width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))

# 绘制堆叠条形组
d[['DC', 'DC - IDC']].plot.barh(
    stacked=True, 
    ax=ax, 
    width=bar_width, 
    position=1
)
# 绘制非堆叠条形组
d[['No Address']].plot.barh(
    stacked=False, 
    color='red', 
    ax=ax, 
    width=bar_width, 
    position=0
)

# 调整y轴刻度位置,对齐两组条形中间
ax.set_yticks([i + bar_width/2 for i in range(len(d.index))])
ax.set_yticklabels(d.index)

# 展示图表
plt.tight_layout()
plt.show()

关键逻辑说明

  • 两次调用plot.barh时都指定同一个ax参数,保证所有条形绘制在同一张画布上
  • position参数控制两组条形在y轴刻度上的偏移,搭配bar_width设置刚好实现并排不重叠的效果
  • 手动调整y轴刻度位置,避免刻度与条形错位

内容的提问来源于stack exchange,提问作者Sergio Polimante

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:00:01