pandas 基于值的条形图的 Matplotlib 不同颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45274183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib different colors for bar graph based on value
提问by thomas.mac
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:
我正在绘制行业和其中所有股票的回报。我希望值 > 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)
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.
到目前为止,这将整个扇区图返回为绿色或红色;如果第一个值 > 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.
我的预期输出是有 11 个图表(目前有),但图表中每只股票的颜色不同,如果股票的回报率 > 100%,则显示绿色,< 100% 显示红色。
回答by Kacper Wolkowski
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.
在使用 Pandas plot() 尝试了几次之后,我没有找到实现您期望的方法,但是您可以直接使用 Matplotlib 轻松实现。
I hope this will help:
我希望这个能帮上忙:
I created sample df:
我创建了示例 df:
df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})
and I create two temp df which will store only values satisfying the condition:
我创建了两个临时 df,它们将只存储满足条件的值:
t1 = df[df['a']<5]
t2 = df[df['a']>=5]
and then just plot it :
然后只是绘制它:
plt.bar(t1.index.values, t1['a'], color='r')
plt.bar(t2.index.values, t2['a'], color='g')
the final result looks like this:
最终结果如下所示:
Is that what you expect?
那是你期望的吗?
回答by Ramon Crehuet
You can achieve your result in a single call to plt.bar
this way:
您可以通过一次调用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)
You also mention in a comment that sectordict[i]
is a dictionary, but you can easily convert a dictionary into a dataframe with:
pd.DataFrame.from_dict
.
你还别说在评论这sectordict[i]
是一本字典,但你可以很容易地转换字典成数据帧有:
pd.DataFrame.from_dict
。