CF84 - 2 months ago 8x
Python Question

# Matplotlib: error with "height" in grouped barchart

I want to produce a barchart with two categories on the x axis and, for each category, 5 different series. I took inspiration from here, and amended the code as follows:

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()
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))

I keep getting the same error:
ValueError: incompatible sizes: argument 'height' must be length 2 or scalar
.

It points at:
ax1.bar(pos, vals, width=width,label=cond,color=cm.Accent(float(i)/n))
.

I understand the problem is with
vals
because it should either be a scalar or have length 2, but I don't know how to solve it. The elements of
vals
are float!

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()
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))

plt.show()