Error for bar chart in matplotlib python 3

Viewed 820

I am trying to make a bar graph (from mean values) that includes error bars (from standard deviation values) using matplotlib, but have been running into an error saying:

'Rectangle' object has no property 'labels'

and if I remove this line:

'Rectangle' object has no property 'rotation'

Some help and clarification into what is happening would be great! Here is an example of what I have so far below:

list1=[1,2,3,4,5,6]
list2=[0.1,0.2,0.3,0.4,0.5,0.6]
list3=['a','b','c','d','e','f']
x = range(len(list1))
y = list1 #contains mean values in list
z = list2 #contains std values in list
l=list3 #contains label names
plt.bar(x, y, yerr=z, color='green', rotation='vertical', label=l)  
plt.show()

Thanks!

2 Answers

IIUC,

list1=[1,2,3,4,5,6]
list2=[0.1,0.2,0.3,0.4,0.5,0.6]
list3=['a','b','c','d','e','f']
x = range(len(list1))
y = list1 #contains mean values in list
z = list2 #contains std values in list
l=list3 #contains label names
rects = plt.bar(x, y, yerr=z, color='green', label=l)
ax = plt.gca()
ax.bar_label(rects)
plt.show()

Output:

enter image description here


list1=[1,2,3,4,5,6]
list2=[0.1,0.2,0.3,0.4,0.5,0.6]
list3=['a','b','c','d','e','f']
x = range(len(list1))
y = list1 #contains mean values in list
z = list2 #contains std values in list
l=list3 #contains label names
rects = plt.barh(x, y, xerr=z, color='green', label=l)
ax = plt.gca()
ax.bar_label(rects)
plt.show()

Output:

enter image description here

The errors result from plt.bar() not knowing the keywords rotation and label, so these arguments are passed on to the lower level plotting functions, but apparently those can't handle them either.

To plot a horizontal bar chart, you can use plt.barh(). Note that you then want to pass the error values as xerr rather than yerr. The keyword for the labels is tick_label.

plt.barh(x, y, xerr=z, color='green', tick_label=l)

horizontal bar plot

Related