Matplotlib:错误"身高"在分组的条形图中

时间:2016-07-21 18:17:29

标签: python matplotlib

我想在x轴上生成一个带有两个类别的条形图,对于每个类别,我想生成5个不同的系列。我从here中获取灵感,并将代码修改如下:

import numpy as np 
import matplotlib.pyplot as plt
from pylab import *
%pylab inline

myarray=np.array([['Series1', 'A',45],
           ['Series2', 'A',47],
           ['Series3', 'A',48],
           ['Series4','A',48],
           ['Series5', 'A',49],
           ['Series6','B',39],
           ['Series7','B',37],
           ['Series8','B',38],     
           ['Series9','B',36],   
           ['Series10','B',38]]) 

fig1=plt.figure()
ax1=fig1.add_subplot(111)
space=0.25

slots=np.unique(myarray[:,0])
categories=np.unique(myarray[:,1])

n=len(slots)
width = (1 - space) / (len(slots))

for i,cond in enumerate(slots):
    print "cond:", cond
    vals = myarray[myarray[:,0] == cond][:,2]
    pos = [j - (1 - space) / 2. + i * width for j in range(1,len(categories)+1)]
    ax1.bar(pos, vals, width=width,label=cond,color=cm.Accent(float(i)/n))

我一直收到同样的错误:ValueError: incompatible sizes: argument 'height' must be length 2 or scalar

它指向:ax1.bar(pos, vals, width=width,label=cond,color=cm.Accent(float(i)/n))

我理解问题出在vals,因为它应该是标量或长度为2,但我不知道如何解决它。 vals的元素是浮动的!

1 个答案:

答案 0 :(得分:1)

import numpy as np
import matplotlib.pyplot as plt
from pylab import *

myarray=np.array([['Series1', 'A',45],
           ['Series2', 'A',47],
           ['Series3', 'A',48],
           ['Series4','A',48],
           ['Series5', 'A',49],
           ['Series1','B',39],
           ['Series2','B',37],
           ['Series3','B',38],
           ['Series4','B',36],
           ['Series5','B',38]])

fig1=plt.figure()
ax1=fig1.add_subplot(111)
space=0.25

slots=np.unique(myarray[:,0])
categories=np.unique(myarray[:,1])

n=len(slots)
width = (1 - space) / (len(slots))

for i,cond in enumerate(slots[::-1]):
    print "cond:", cond
    vals = myarray[myarray[:,0] == cond][:,2]
    pos = [j - (1 - space) / 2. + i * width for j in range(1,len(categories)+1)]
    print(float(i)/n)
    ax1.bar(pos, vals, width=width,label=cond,color=cm.Accent(1-float(i+1)/n))

plt.show()

enter image description here