0

So I have this horizontal barplot and I want to highlight certain labels (or keywords) with other colors. This is my horizontal barplot: enter image description here

I want to make the keyword 'nature' and 'panorama' to be red color. I tried this code but it doesn't work:

f, ax = plt.subplots(figsize=(15,15))
plt.autoscale(enable=True, axis='y', tight=True)                    # tight layout
plt.barh(df['keywords'], df['number'])                              # base barplot with blue color
plt.barh(df[df['keywords']=='nature'], df['number'], color='red')   # overlay barplot with red color
plt.barh(df[df['keywords']=='panorama'], df['number'], color='red') # overlay barplot with red color
ax.tick_params(labelsize=18)
plt.title('Difference average of cluster 3')
  • Does this answer your question? [Matplotlib - Changing the color of a single x-axis tick label](https://stackoverflow.com/questions/42878462/matplotlib-changing-the-color-of-a-single-x-axis-tick-label) – Diziet Asahi Mar 10 '20 at 16:05
  • it's not actually. because it takes the position of the label, while I want to highlight the label based on the keywords. – Jack Zaki Zakiul Fahmi Jailani Mar 10 '20 at 16:27

1 Answers1

1

You might try to add two columns, namely 'number_red','number_blue':

df['number_red']=np.where((df['keywords']=='nature')|(df['keywords']=='panorama'),df['number'],0)
df['number_blue']=np.where((df['keywords']!='nature')&(df['keywords']!='panorama'),df['number'],0)

'number_red' only show numbers that belong to 'panorama' or 'nature', while fill numbers of keywords with zero. 'number_blue' does the opposite. (You can print df to have a look) So if you just overlay these two columns in your bar plot:

plt.barh(df['keywords'],df['number_red'],  color='red')
plt.barh(df['keywords'],df['number_blue'], color='blue')

The numbers will be complementary, but show you the desired color. I hope this helps!

tianlinhe
  • 991
  • 1
  • 6
  • 15