Reputation: 7
I have a horizontal bar chart, and want to highlight certain bars (with unique colors) based on string values. I tried 'axhspan' function or using masks, but none of them work well with string ticks. I know there are similar questions for cases where ticks are numbers (int, float) rather than string.
In my case, I have data for 50 countries, and want to highlight some groups of countries with a different color. For example: US, Canada with yellow; France, UK with blue; Japan, HongKong with orange, etc..
Here's is a simplified version of my code, could anyone show me how set a different color for a subgroup (i.e.'us' and 'canada'). Thanks!
country_names = ['usa','brazil','canada']
country_rank = pd.Series(np.random.randn(3), index=country_names)
import matplotlib.pyplot as plt
plt.rcdefaults()
fig, ax = plt.subplots(figsize=(10,15)) # set figure size
y_pos = np.arange(len(country_names))
error = np.zeros(len(country_names))
ax.barh(y_pos, country_rank, color='green', xerr=error, align='center', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(country_names)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Strategy Score') # add comments on x, y labels.
ax.set_title('Global Large Cap Index Allocation Model')
ax.set_yticklabels(country_names, ha='left', minor=False) #align y tick_labels to the left
ax.yaxis.tick_right() #move y tickers to the right
plt.tight_layout() #avoid text overlap
plt.show()
Upvotes: 0
Views: 1609
Reputation: 3106
You can create a list of colors for each country. For countries which you don't want to mark, you will use default color (i.e. 'g'). You can find the correct country to highlight by indexing country names. Like this:
#defalut color
color = [ 'g' for i in country_names]
#highlight usa:
color[ country_names.index("usa") ] = "b"
#highlight canada:
color[ country_names.index("canada") ] = "r"
ax.barh(y_pos, country_rank, color=color, xerr=error, align='center', ecolor='black')
If you need to set the same color for some countries in a list of selected countries, and this list isn't so big.... (There are only 196 countries in the world), you can do it in a simple loop
for name in selected_coutries:
color[ country_names.index(name) ] = "y"
Upvotes: 1