matplotlib堆叠条形图更改误差条的位置

mrwjdhj3  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(149)

堆积条形图中的误差线重叠。是否有办法更改误差线的x位置,但使主条形线保持在同一位置?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import numpy as np
from statistics import mean, stdev, median

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()

for i in range(0, len(types)):
    means = list(map(lambda x: results[x][types[i]][0], results.keys()))
    errs = list(map(lambda x: results[x][types[i]][1], results.keys()))
    ax.bar(results.keys(), means, width, yerr=errs, label=types[i], bottom=bottom, color=colors3[i], error_kw=dict(capsize=5))
    for k in range(0, len(means)):
        bottom[k] = bottom[k] + means[k]

ax.grid(True)
ax.set_axisbelow(True)
plt.legend(types, loc='upper right')
#plt.savefig('img/StackOverflow.png', bbox_inches='tight', dpi=300)
plt.show()
w7t8yxp5

w7t8yxp51#

使用plt.errorbar单独绘制条形图,然后单独绘制误差条形图
为了做到这一点,您需要切换到使用数值而不是分类数据(x_vals),我还必须将一些列表更改为numpy数组,以允许元素加法。

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 = np.array([0, 0, 0])
fig, ax = plt.subplots()

for i in range(0, len(types)):
    means = np.array(list(map(lambda x: results[x][types[i]][0], results.keys())))
    errs = list(map(lambda x: results[x][types[i]][1], results.keys()))
    x_vals = np.array([1, 2, 3])
    ax.bar(x_vals, means, width, label=types[i], bottom=bottom, color=colors3[i], error_kw=dict(capsize=5))
    
    ax.errorbar(x_vals - 1/10 + i/10, means+bottom, yerr=errs, linestyle='none', color='black', capsize=5)
    # above line sets the errorbar loctions, adding i/10 each time
    plt.xticks(ticks=x_vals, labels=results.keys())
    # reset the xticks to their names
    
    for k in range(0, len(means)):
        bottom[k] = bottom[k] + means[k]
    print(x_vals, means)

ax.grid(True)
ax.set_axisbelow(True)
plt.legend(types, loc='upper right')
#plt.savefig('img/StackOverflow.png', bbox_inches='tight', dpi=300)
plt.show()

相关问题