欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python中matplotlib条件背景颜色的实现

程序员文章站 2022-05-25 21:45:08
如何根据图表中没有的变量更改折线图的背景颜色?例如,如果我有以下数据帧: import numpy as np import pandas as pd d...

如何根据图表中没有的变量更改折线图的背景颜色?例如,如果我有以下数据帧:

import numpy as np
import pandas as pd

dates = pd.date_range('20000101', periods=800)
df = pd.dataframe(index=dates)
df['a'] = np.cumsum(np.random.randn(800)) 
df['b'] = np.random.randint(-1,2,size=800)

如果我做df.a的折线图,如何根据该时间点'b'列的值更改背景颜色?

例如,如果在该日期b = 1,则该日期的背景为绿色。

如果b = 0,则该日期的背景应为黄色。

如果b = -1那么背景那个日期应该是红色的。

添加我最初考虑使用axvline的解决方法,但@jakevdp回答正是看起来因为不需要for循环:首先需要添加一个'i'列作为计数器,然后整个代码看起来像:

dates = pd.date_range('20000101', periods=800)
df = pd.dataframe(index=dates)
df['a'] = np.cumsum(np.random.randn(800)) 
df['b'] = np.random.randint(-1,2,size=800)
df['i'] = range(1,801)

# getting the row where those values are true wit the 'i' value
zeros = df[df['b']== 0]['i'] 
pos_1 = df[df['b']==1]['i']
neg_1 = df[df['b']==-1]['i']

ax = df.a.plot()

for x in zeros:
 ax.axvline(df.index[x], color='y',linewidth=5,alpha=0.03)
for x in pos_1:
  ax.axvline(df.index[x], color='g',linewidth=5,alpha=0.03)
for x in neg_1:
  ax.axvline(df.index[x], color='r',linewidth=5,alpha=0.03)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。