我正在尝试绘制带有多个条形的直方图-val[0][0]
和val[1][0]
以及不对称误差线error1[0]
和error2[0]
。绘图将具有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()
答案 0 :(得分:0)
我只是显示相关内容并突出显示通过评论# <-----
修改的行。
主要问题:
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) # <-----