【问题标题】:Matplotlib different colors for bar graph based on valueMatplotlib 基于值的条形图不同颜色
【发布时间】:2017-07-24 06:45:45
【问题描述】:

我正在绘制行业及其中所有股票的回报。我希望值 > 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)

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

我的预期输出是有 11 个图表(目前是这样),但图表中每只股票的颜色不同,如果股票的回报率 > 100%,则显示绿色,

【问题讨论】:

  • 你能从你的 df 添加几行吗?单个部门

标签: python pandas matplotlib yahoo-finance


【解决方案1】:

在尝试使用 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')

最终结果如下:

这是你所期望的吗?

【讨论】:

  • 这是我希望图表的样子,但我的ectordict[i] 不是df,而是字典
  • 如果您要添加一些示例数据,我可以提供更多帮助,并根据您的示例自定义此图。
【解决方案2】:

您可以通过以下方式通过一次调用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.

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2016-10-17
    • 2015-09-27
    相关资源
    最近更新 更多