简体   繁体   English

matplotlib 用不对称误差线绘制直方图

[英]matplotlib plotting histogram with asymmetric error bars

I am trying to plot histogram with multiple bars - val[0][0] and val[1][0] together with asymmetric errorbars error1[0] and error2[0] respectively.我正在尝试使用多个条形图 plot 直方图 - val[0][0]val[1][0]以及不对称的误差线 error1 error1[0]error2[0]分别。 Plot will have 7 dual-data bars. Plot 将有 7 个双数据条。 Below is the code I have, but it gives error ValueError: incompatible sizes: argument 'height' must be length 2 or scalar .下面是我的代码,但它给出了错误ValueError: incompatible sizes: argument 'height' must be length 2 or scalar

import numpy as np
import matplotlib.pyplot as plt

val = [[26.0,35.0,-6.0,22.0,38.0,19.0,12.0],
                      [28.6,36.1,4.6,27.2,43.7,11.2,25.1]]


error1=[[17.0,17.0],[15.0,15.0],[18.0,13.0],[13.0,15.0],[3.0,2.0],[9.0,8.0],[15.0,12.0]]
error2=[[2.4,2.4],[3.7,2.4],[6.4,4.4],[9.4,10.3],[2.1,2.8],[30.4,7.8],[2.5,2.5]]

length = len(val)
x_labels = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']

fig, ax = plt.subplots()
barwidth = 0.25 
x = np.arange(length)

ax.bar(x, val[0][0], barwidth, label='category1', yerr=[error1[0]]) 
ax.bar(x + 1*barwidth, val[0][1], barwidth, label='category2', yerr=[error2[0]])
ax.set_ylabel('values')
ax.set_ylim(0,75)
ax.set_xticks(x + barwidth + barwidth/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('X')
ax.set_title('Plot')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()

I am just showing the relevant and highlighting the lines I modified by a comment # <----- .我只是显示相关并突出显示我通过评论修改的行# <-----

Main issues:主要问题:

  • You were using wrong length and wrong sb-list for plotting.您使用错误的长度和错误的 sb-list 进行绘图。
  • Use width keyword for bar width对条形宽度使用width关键字
  • Use errors in a 2xn shape.使用 2xn 形状的错误。 This you get by transforming to array and then taking transpose您可以通过转换为数组然后进行转置来获得

error1=np.array([[17.0,17.0],[15.0,15.0],[18.0,13.0],[13.0,15.0],
                 [3.0,2.0],[9.0,8.0],[15.0,12.0]]) # <----- Convert to array 
error2=np.array([[2.4,2.4],[3.7,2.4],[6.4,4.4],[9.4,10.3],
                 [2.1,2.8],[30.4,7.8],[2.5,2.5]]) # <----- Convert to array 

length = len(val[0]) # <----- Choose the correct length using [0] index
x_labels = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']

fig, ax = plt.subplots()
barwidth = 0.25 
x = np.arange(length)

ax.bar(x, val[0], width=barwidth, 
       label='category1', yerr=error1.T) # <----- 
ax.bar(x + 1*barwidth, val[1], barwidth, label='category2', yerr=error2.T) # <-----

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM