通过这个例子, http://matplotlib.org/examples/pylab_examples/barchart_demo.html
我想生成动态条形图。到目前为止,我有以下脚本。
import sys
import matplotlib.pyplot as plt
import numpy as np
groups = int(sys.argv[1])
subgroup = int(sys.argv[2])
fig, ax = plt.subplots()
index = np.arange(groups)
print index
bar_width = 1.0 / (subgroup + 1)
print bar_width
mainlist = []
for x in range(0, groups):
#print x
templist = []
for num in range(0, subgroup):
templist.append(num+1)
#print templist
mainlist.append(templist)
print mainlist
for cnt in range(0,subgroup):
plt.bar(index + (bar_width * cnt), mainlist[cnt], bar_width)
plt.savefig('odd_bar_chart.png')
当我为组和子组传递相同的值时,这可以正常工作,
> odd_bar_chart.py 3 3
> odd_bar_chart.py 2 2
但如果我传递不同的值,
odd_bar_chart.py 3 2 odd_bar_chart.py 2 3
它会出现以下错误 AssertionError:不兼容的大小:参数'height'必须是length {first argument}或scalar
现在我不知道hw身高出现了吗? 谁能告诉我这里有什么问题?
答案 0 :(得分:2)
看看docs for plt.bar
。这里前两个参数是left
和height
,它们指的是条形左侧的值和它的高度。
您的错误消息通知您第二个参数height
应与第一个参数或标量(单个值)的长度相同。
错误:
在最后的迭代中,您将高度mainlist[cnt]
绘制在左侧位置index + (bar_width * cnt)
上。显然,您正在尝试调整x
位置,以使用bar_with*cnt
在空间上分隔条形图,因此这是一个标量。 left
的长度由index
给出,index = np.arange(groups)
由group
生成,因此长度为subgroup
。但是高度的长度由templist
给出,这是在subgroup
(其长度为mainlist
)附加到{{1}}时完成的。
因此,您的错误会出现在生成数据的方式中。通常最好是手动粘贴(如在您引用的示例中所做的那样),或使用something form numpy.random
生成一组随机数。