基于轴字符串值

时间:2018-05-17 19:39:13

标签: python colors bar-chart

我有一个水平条形图,并希望根据字符串值突出显示某些条形(具有唯一颜色)。我试过'axhspan'函数或使用蒙版,但它们都不适用于字符串滴答。我知道对于tick是数字(int,float)而不是string的情况有类似的问题。

就我而言,我有50个国家/地区的数据,并希望突出显示一些颜色不同的国家/地区。例如:美国,加拿大黄色;法国,英国与蓝色;日本,香港用橙等。

这是我的代码的简化版本,任何人都可以告诉我如何为子组设置不同的颜色(即'us'和'canada')。谢谢!

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()

1 个答案:

答案 0 :(得分:1)

您可以为每个国家/地区创建颜色列表。对于您不想标记的国家/地区,您将使用默认颜色(即' g')。您可以通过索引国家/地区名称找到要突出显示的正确国家/地像这样:

#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')

如果您需要为所选国家/地区列表中的某些国家/地区设置相同的颜色,并且此列表不是那么大......(世界上只有196个国家/地区),您可以执行此操作在一个简单的循环中

for name in selected_coutries:
    color[ country_names.index(name) ] = "y"