首页 > 编程 > Python > 正文

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

2019-11-25 11:47:09
字体:
来源:转载
供稿:网友

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

import numpy as npimport pandas as pddates = 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' valuezeros = 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)

总结

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表