I have the following pandas dataframe:
a b
bob 23 25
john 13 21
paul 20 19
david 17 14
michael 14 24
neil 22 11
df.plot(kind='barh')
I used the pandas plot function. I want to make a barh chart with all the rows(names) having a different colors is there a way to do this?
I need all person to have different colored bars.
You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.
It appears that Pandas only supports using the colormap attribute, which applies the same map to each row in your chart, e.g.:
df.plot(kind='barh', colormap='RdBu')
For your purposes, you need to use Matplotlib directly.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'a':[23, 13, 20, 17, 14, 22],
'b':[25, 21, 19, 14, 23, 11]},
index=['bob', 'john', 'paul', 'david', 'michael', 'neil'])
a_vals = df.a
b_vals = df.b
ind = np.arange(df.shape[0])
width = 0.35
# Set the colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']
def autolabel(bars):
# attach some text labels
for bar in bars:
width = bar.get_width()
ax.text(width*0.95, bar.get_y() + bar.get_height()/2,
'%d' % int(width),
ha='right', va='center')
# make the plots
fig, ax = plt.subplots()
a = ax.barh(ind, a_vals, width, color = colors) # plot a vals
b = ax.barh(ind + width, b_vals, width, color = colors, alpha=0.5) # plot b vals
ax.set_yticks(ind + width) # position axis ticks
ax.set_yticklabels(df.index) # set them to the names
ax.legend((a[0], b[0]), ['a', 'b'], loc='center right')
autolabel(a)
autolabel(b)
plt.show()
Please refer to the following examples:
1 - matplotlib bar charts
2- changing individual colors on bar chart
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With