![](/img/trans.png)
[英]How to set different colors on matplotlib bar graph based on the group of data?
[英]Matplotlib different colors for bar graph based on value
我正在繪制部門及其所有股票的收益。 我想將值> 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)
到目前為止,這會將整個扇區圖形返回為綠色或紅色。 如果第一個值大於100,則所有庫存均為綠色,反之亦然。
我的預期輸出是有11張圖(當前它會這樣做),但是圖中的每只股票都有不同的顏色,如果股票回報率> 100%,則顯示綠色,而<100%,則顯示紅色。
在使用Pandas plot()進行了幾次嘗試之后,我沒有找到實現您所期望的方法,但是您可以直接使用Matplotlib輕松地做到這一點。
我希望這個能幫上忙:
我創建了示例df:
df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})
並且我創建了兩個temp 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
以下方式一次調用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
輕松地將字典轉換為數據pd.DataFrame.from_dict
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.