[英]matplotlib plotting histogram with asymmetric error bars
我正在嘗試使用多個條形圖 plot 直方圖 - val[0][0]
和val[1][0]
以及不對稱的誤差線 error1 error1[0]
和error2[0]
分別。 Plot 將有 7 個雙數據條。 下面是我的代碼,但它給出了錯誤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()
我只是顯示相關並突出顯示我通過評論修改的行# <-----
。
主要問題:
width
關鍵字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.