Matplotlib基于值的条形图的不同颜色 [英] Matplotlib different colors for bar graph based on value
问题描述
我正在绘制部门及其所有股票的收益.我希望值> 100为绿色,而< 100为红色.这是我的代码:
I'm plotting returns for sectors and all the stocks in them. I would like to have the values > 100 to be green, and < 100 to be red. Here's my code:
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,则所有库存均为绿色,反之亦然.
So far this is returning the whole sector graphs as green or red; if the first value is > 100 all stocks will be green and vice versa.
我的预期输出是有11张图表(当前执行此操作),但是图表中每只股票具有不同的颜色,如果股票回报率> 100%,则显示绿色,而< 100%显示为红色.
My expected output is to have 11 graphs (which it currently does), but with different colors for each stock within the graph, if stock had > 100% return then it shows green and < 100% it shows red.
推荐答案
在使用Pandas plot()进行了几次尝试之后,我没有找到实现您所期望的方法,但是您可以直接使用Matplotlib轻松地做到这一点.
After few tries with Pandas plot() I didn't find a way to achieve what you expect but you can easily do that with Matplotlib directly.
我希望这会有所帮助:
我创建了示例df:
df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})
然后我创建两个temp df,它将仅存储满足条件的值:
and I create two temp df which will store only values satisfying the condition:
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')
最终结果如下:
这是您的期望吗?
这篇关于Matplotlib基于值的条形图的不同颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!