如何通过指定错误栏的下限和上限值将误差条添加到matplotlib中的条形图

时间:2017-08-16 16:30:22

标签: python matplotlib bar-chart

我正在尝试绘制python中具有最小值和最大值的条形图。我可以添加标准偏差条,但这不是我想要的。请看附图。我可以很容易地为散点图定义这个,但不能用于条形图。有人可以帮我这个吗?

enter image description here

这是我的代码:

# here is some example to for plotting

import matplotlib.pyplot as plt  

Label_L4L5_DP = ['Upright', 'Flexion', 'Extension', 'Bending', 'Rotation']

L4L5DP_Upr_Model  = 0.618
L4L5DP_Flex_Model = 1.137
L4L5DP_Exte_Model = 0.573
L4L5DP_Bend_Model = 1.155
L4L5DP_Rot_Model  = 1.181

L4L5DP_Wilke     = [0.5, 1.1, 0.6, 0.6, 0.62]    
L4L5DP_Sato      = [0.53912500000000008, 1.3240000000000001, 0.60024999999999995, 0, 0]    
L4L5DP_Takahashi = [0.645, 2.305, 0, 0, 0]

L4L5DP_Model     = [0.61899333208571361, 1.1375315303045039,0.57351447125529353,1.1552968123236578,1.1817117576612417]  

Std_L4L5_Sato = [0.16732411474440856, 0.2077287895309651, 0.17525320967103569, 0, 0]

# Setting the positions and width for the bars
pos = [0, 1, 2, 3, 4]
width = 0.2 

# Plotting the bars
fig, ax = plt.subplots(figsize=(8,6))

plt.bar(pos, L4L5DP_Model, width,
                 alpha=0.5,
                 color='r',
                 #yerr= 0,
                 #label=Label_L4L5_DP[3]
                 )

plt.bar([p + width for p in pos], L4L5DP_Wilke, width,
                 alpha=0.5,
                 color='g',
                 #yerr= 0,
                 #label=Label_L4L5_DP[0]
                 )

plt.bar([p + 2*width for p in pos], L4L5DP_Sato, width,
                 alpha=0.5,
                 color='b',
                    yerr= Std_L4L5_Sato,
                 #label=Label_L4L5_DP[1]
                 )

plt.bar([p + 3*width for p in pos], L4L5DP_Takahashi, width,
                 alpha=0.5,
                 color='k',
                 #yerr= 0,
                 #label=Label_L4L5_DP[2]
                 )

#    plt.errorbar(Sato_Mean_L4L5_Upr,Sato_Mean_L4L5_Upr, xerr = offsets_Sato_L4L5_Upr, fmt='b')
#    plt.errorbar([p + 3*width for p in pos], Sato_Mean_L4L5_F53, xerr = offsets_Sato_L4L5_F53, fmt='b')
#    plt.errorbar([p + 3*width for p in pos], Sato_Mean_L4L5_E30, xerr = offsets_Sato_L4L5_E30, fmt='b')

# Setting axis labels and ticks
ax.set_ylabel('Disc pressure [MPa]')
ax.set_title('L4L5')
ax.set_xticks([p + 1.5 * width for p in pos])
ax.set_xticklabels(Label_L4L5_DP)

# Setting the x-axis and y-axis limits
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(L4L5DP_Wilke + L4L5DP_Sato + L4L5DP_Takahashi + L4L5DP_Model) * 1.5])

# Adding the legend and showing the plot
plt.legend(['Model', 'Wilke', 'Sato', 'Takahashi'], loc='upper left')
plt.grid()
plt.show()

1 个答案:

答案 0 :(得分:2)

yerr选项可以采用包含下行错误和错误值的两项列表

Std_L4L5_Sato = [[0.1, 0.1, 0.1, 0, 0], [1, 1, 1, 0, 0]]

此示例绘制非对称误差线。

如果您想要指定最小值和最大值,则只需根据中心值L4L5DP_Sato计算上下错误:

import numpy
L4L5DP_Sato = numpy.array(L4L5DP_Sato)
Std_L4L5_Sato = [L4L5DP_Sato - min_values, max_values - L4L5DP_Sato]