SR34
SR34

Reputation: 47

Matplotlib bar chart different colors for each bar

I am trying to create a simple horizontal bar chart but I want to spruce it up with each bar using a teams color. I thought it would be as simple as passing each teams hex color to the color parameter as an array but what I get is each bar displaying as the first color provided in the array.

data.plot(kind="barh", color=['#A71930', '#DF4601', '#AB0003', '#003278', '#FF5910', '#0E3386', '#BA0021', '#E81828', '#473729', '#D31145', '#0C2340', '#005A9C', '#BD3039', '#EB6E1F', '#C41E3A', '#33006F', '#C6011F', '#004687', '#CE1141', '#134A8E', '#27251F', '#FDB827', '#0C2340', '#FD5A1E', '#00A3E0', '#ffc52f', '#003831', '#005C5C', '#E31937', '#8FBCE6'])
plt.title('Team Ranking Marginal Doller Spent per Marginal Win')
plt.ylabel('Team')
plt.xlabel('Marginal Doller Spent per Marginal Win')
plt.style.use('fivethirtyeight')
plt.gcf().set_size_inches(10, 12)
plt.show()

Here is the result enter image description here

Upvotes: 3

Views: 5308

Answers (1)

researchgrant
researchgrant

Reputation: 41

It looks like you are using pandas to plot, which returns an axis object. You can modify the color of each bar by iterating through the patches:

colors=['#A71930', '#DF4601', '#AB0003', '#003278', '#FF5910', '#0E3386', '#BA0021', '#E81828', '#473729', '#D31145', '#0C2340', '#005A9C', '#BD3039', '#EB6E1F', '#C41E3A', '#33006F', '#C6011F', '#004687', '#CE1141', '#134A8E', '#27251F', '#FDB827', '#0C2340', '#FD5A1E', '#00A3E0', '#ffc52f', '#003831', '#005C5C', '#E31937', '#8FBCE6']
ax=data.plot(kind='barh')
for patch,color in zip(ax.patches,colors):
    patch.set_facecolor(color)

It's a bit of a work around, but its nice to get to know how to access the pandas generated figures in case the built-in functions leave something to be desired.

(Edited a variable name because someone in the comments said it was ugly)

Upvotes: 3

Related Questions