Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring only certain bars in matplotlib barplot with different colors

df=pd.DataFrame([770,215,179,107,83,82,70,60,57,54,52],index = ['A','B','C','D','E','F','G','H','I','J','K']) 

ax = df.plot(kind='bar',stacked = False,alpha=0.75, rot=45,fontsize=20)
ax.legend_.remove()
for p in ax.patches:
        ax.annotate(np.round(p.get_height(),decimals=0).astype(np.int64), (p.get_x()+p.get_width()/2., p.get_height()), ha='center', va='center', xytext=(2, 10), textcoords='offset points',fontsize=20)
plt.ylabel('y ',fontsize=25)
plt.title('x',fontsize=30)
plt.show()
plt.save()
plt.close()

gave me : enter image description here

Now, I would just like to color B and H with different colors lets say red and orange. I would be more than thankful for any kind suggestion to achieve that. Thank you.

like image 393
Acerace.py Avatar asked Mar 26 '26 18:03

Acerace.py


1 Answers

Try this:

ax.patches[df.index.get_indexer(['B'])[0]].set_facecolor('r')

ax.patches[df.index.get_indexer(['H'])[0]].set_facecolor('orange')

enter image description here

like image 189
MaxU - stop WAR against UA Avatar answered Mar 28 '26 07:03

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!