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

yipeiwu_com5年前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)
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)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python实现把回车符\r\n转换成\n

最近在做cocos2d-x的简明配置,发现有的朋友的文本编辑器,自动将\r\n截断成\n,(在unix上换行使用\n,windows上,换行使用的是\r\n)于是,写了这个脚本,希望对一...

使用Python读取安卓手机的屏幕分辨率方法

直接代码吧: import os import sys import json import re def _get_screen_size(): '获取手机屏幕大小' size...

详解django中使用定时任务的方法

今天介绍在django中使用定时任务的两种方式。 方式一: APScheduler 1)安装: pip install apscheduler 2)使用: from apsc...

深入理解Python中的 __new__ 和 __init__及区别介绍

本文的目的是讨论Python中 __new__ 和 __ini___ 的用法。 __new__ 和 __init__ 的区别主要表现在:1. 它自身的区别;2. 及在Python中新式类...

Python第三方库face_recognition在windows上的安装过程

实际上face_recognition这个项目尤其是dlib更适用于Linux系统。经过我的测试,在性能方面,编译同样规格的项目,这个工具在Windows 10 上大约是Ubuntu上的...