如何将条形颜色链接到yticks?

时间:2019-04-22 02:45:48

标签: python matplotlib charts colors bar-chart

我有以下数据资料:

enter image description here

我想每年制作一张条形图,排序,每个人用一种颜色。 我只是得到固定的颜色,就像这样:

enter image description here

enter image description here

我使用了以下代码:

color = ['red','blue','green','orange']  
for i in range (2007, 2010):
   fig, ax = plt.subplots()
   x = df2.loc[i,].sort_values()
   y = [x.index[0], x.index[1], x.index[2], x.index[3]]
   ax.barh(y,x, color=color)
   plt.title(i)

如何将颜色链接到名称?

1 个答案:

答案 0 :(得分:1)

您可以创建一个将名称链接到颜色的字典,然后在绘制为时使用该信息

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 6))

color = ['red','blue','green','orange']  
colors_dict = {k:v for k,v in zip(df2.columns, color)}

for i, ax in zip(range(2007, 2011), axes.flatten()):
    x = df2.loc[i,].sort_values()
    color = [colors_dict[i] for i in x.index]
    ax.barh(x.index, x, color=color)
    ax.set_title(i)
plt.tight_layout()    

enter image description here