Matplotlib:ValueError:不兼容的大小:参数'height'必须是长度2或标量

时间:2017-09-18 14:13:36

标签: python matplotlib

我正在使用matplotlib绘制条形图。之前我在两个位置只有两组酒吧(总共4个酒吧)。所以my_list是一个4x2矩阵,我的脚本运行得很好。

我添加了另一组数据(现在我的数组是6x2)并将这些新条添加到我的y1_means。但是,我收到以下错误:

ValueError: incompatible sizes: argument 'height' must be length 2 or scalar

*更新*

我添加了另一个栏(rects3)并将y_means缩减为两个值。它有效,但最后两个条形堆叠。

我查看了与此错误相关的其他帖子,但找不到我的解决方案。有人可以帮忙吗? 这是我的剧本:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt

mylist = [[1061.8065108865587, 242.42977414163315], 
          [0.17619757021099161, 0.090235256942903783], 
          [0.12829524580453561, 0.083100278521638746], 
          [580.78192382619045, 367.56899594357981], 
          [0.76475391750505795, 0.42257691834032352], 
          [0.50712851564326855, 0.14217924391430981]]

###### Plot Script ######
N = 2

y1_means = (mylist[1][0], mylist[5][0])
y1_std = (mylist[1][1], mylist[5][1])

ind = np.arange(N)  # the x locations for the groups
width = 0.3       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, y1_means, width, color='r', alpha=0.3, yerr=y1_std)

y2_means = (mylist[1][0], mylist[4][0])
y2_std = (mylist[1][1], mylist[4][1])
rects2 = ax.bar(ind + width, y2_means, width, color='b', alpha=0.3, yerr=y2_std)

y3_means = (mylist[2][0], mylist[5][0])
y3_std = (mylist[2][1], mylist[5][1])
rects3 = ax.bar(ind + width, y3_means, width, color='b', alpha=0.3, yerr=y3_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('RTT')
ax.set_xticks(ind + width / 2)
#ax.grid(True)
ax.yaxis.grid('on')
ax.set_xticklabels(('Label-1', 'Label-2'))
fig.tight_layout(rect=[0, 0.05, 1, 0.95])
plt.figlegend( (rects1[0], rects2[0], rects3[0]), ('Scen-1', 'Scen-2', 'Scen-3'),
                    loc = 'lower center', ncol=5, labelspacing=0. )    
plt.show()

1 个答案:

答案 0 :(得分:1)

我最终解决了这个问题。我需要添加另一个条形图。所以每个柱y_means取两个值并更新柱的位置!这是我更新的代码:

###### Plot Script ######
N = 2

y1_means = (mylist[0][0], mylist[3][0])
y1_std = (mylist[0][1], mylist[3][1])

ind = np.arange(N)  # the x locations for the groups
width = 0.3       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width, y1_means, width, color='r', alpha=0.3, yerr=y1_std)

y2_means = (mylist[1][0], mylist[4][0])
y2_std = (mylist[1][1], mylist[4][1])
rects2 = ax.bar(ind, y2_means, width, color='b', alpha=0.3, yerr=y2_std)

y3_means = (mylist[2][0], mylist[5][0])
y3_std = (mylist[2][1], mylist[5][1])
rects3 = ax.bar(ind + width, y2_means, width, color='b', alpha=0.3, yerr=y2_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('RTT')
ax.set_xticks(ind + width / 2)
#ax.grid(True)
ax.yaxis.grid('on')
ax.set_xticklabels(('Label-1', 'Label-2'))
fig.tight_layout(rect=[0, 0.05, 1, 0.95])
plt.figlegend( (rects1[0], rects2[0], rects3[0]), ('Scen-1', 'Scen-2', 'Scen-3'),
                    loc = 'lower center', ncol=5, labelspacing=0. )
plt.show()