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

Matplotlib堆叠柱状图:如何调整误差棒X位置且保留主柱位置?

堆叠柱状图误差棒重叠解决方案(保持主柱位置不变调整误差棒X轴)

可以实现。Matplotlib的柱状图容器允许单独修改误差棒的位置,无需移动主柱状图。核心思路是在绘制每个类型的堆叠柱后,手动调整对应误差棒的X轴坐标,给不同类型的误差棒添加微小偏移,避免重叠。

修改后的完整代码:

import matplotlib.pyplot as plt
import numpy as np

colors3 = ['#7ac0f8', '#2196f3', '#1a78c2']
width = 0.6
results = {'Group 1': {'Type A': [24.21, 32.08], 'Type B': [11.35, 6.59], 'Type C': [45.64, 21.87]}, 'Group 2': {'Type A': [19.41, 17.39], 'Type B': [10.16, 8.72], 'Type C': [21.25, 11.57]}, 'Group 3': {'Type A': [11.4, 9.75], 'Type B': [5.73, 6.98], 'Type C': [6.4, 13.38]}}
types = ['Type A', 'Type B', 'Type C']

bottom = [0, 0, 0]
fig, ax = plt.subplots()

# 给每个类型的误差棒设置偏移,三个类型分别左移、居中、右移
offsets = [-width/8, 0, width/8]

for i in range(len(types)):
    means = [results[group][types[i]][0] for group in results.keys()]
    errs = [results[group][types[i]][1] for group in results.keys()]
    # 绘制柱状图并获取容器
    bar_container = ax.bar(results.keys(), means, width, yerr=errs, label=types[i], 
                           bottom=bottom, color=colors3[i], error_kw=dict(capsize=5))
    
    # 调整当前类型误差棒的X位置
    offset = offsets[i]
    errorbar = bar_container.errorbar
    # 修改误差棒竖线的X坐标
    for line in errorbar.lines:
        x_data = line.get_xdata()
        line.set_xdata(x_data + offset)
    # 修改误差棒横帽的X坐标
    for cap in errorbar.caps:
        x_data = cap.get_xdata()
        cap.set_xdata(x_data + offset)
    
    # 更新堆叠底部位置
    for k in range(len(means)):
        bottom[k] += means[k]

ax.grid(True)
ax.set_axisbelow(True)
plt.legend(types, loc='upper right')
plt.show()

关键说明:

  • 定义offsets列表,给每个类型的误差棒分配不同的X偏移量,这里用width/8作为偏移幅度,既保证误差棒错开,又不会偏离主柱太远。
  • 调用ax.bar后获取返回的BarContainer对象,通过其errorbar属性访问误差棒的线条和横帽元素。
  • 分别修改误差棒竖线和横帽的X坐标数据,实现位置偏移。
  • 主柱状图的位置保持完全不变,仅调整误差棒位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:05:17