Matplotlib 基于值的条形图的不同颜色

Matplotlib different colors for bar graph based on value

我正在为行业及其中的所有股票绘制 returns。我希望值 > 100 为绿色,< 100 为红色。这是我的代码:

sector_lst = ['XLK','XLF','XLE']  ## etc.

for i in sector_lst:                   
    fig = plt.figure(figsize=(12, 8)) 

    for x in sectordict[i]:                #sectordict[i] is all the stocks in a sector (so AAPL, GOOG, etc. for tech) 
        if pct_change[x] > 1:              
             pct_change[sectordict[i]].plot(kind='bar',color='g') 

        ##if pct_chg < 1
        else:                              
             pct_change[sectordict[i]].plot(kind='bar',color='r') 


plt.title(i)

到目前为止,这是 return 将整个扇区图设置为绿色或红色;如果第一个值 > 100,则所有股票都将为绿色,反之亦然。

我的预期输出是有 11 个图表(目前是这样),但图表中的每只股票都有不同的颜色,如果股票 > 100% return 则它显示绿色和 < 100%它显示为红色。

在尝试使用 Pandas plot() 几次后,我没有找到实现您期望的方法,但您可以直接使用 Matplotlib 轻松实现。

希望对您有所帮助:

我创建了示例 df:

df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})

我创建了两个临时 df,它将只存储满足条件的值:

t1 = df[df['a']<5]
t2 = df[df['a']>=5]

然后绘制它:

plt.bar(t1.index.values, t1['a'], color='r')
plt.bar(t2.index.values, t2['a'], color='g')

最终结果如下所示:

这是你期望的吗?

您可以通过这种方式一次调用 plt.bar 来获得结果:

df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})
df['colors'] = 'r'
df.loc[df.a>=5,'colors'] = 'g'
plt.bar(df.index, df.a, color=df.colors)

您还在评论中提到 sectordict[i] 是一个字典,但您可以使用以下方法轻松地将字典转换为数据框: pd.DataFrame.from_dict.