• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-08) 31次浏览 已收录 0个评论

这篇文章主要给大家介绍了关于python中matplotlib条件背景颜色的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

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

 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) d<strong style="color:transparent">来源gaodaima#com搞(代@码网</strong>f = 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)

总结

以上就是python中matplotlib条件背景颜色的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中matplotlib条件背景颜色的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址