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

yipeiwu_com6年前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设计】的支持。

相关文章

django的分页器Paginator 从django中导入类

django的分页器Paginator 从django中导入类

先创建表,然后生成批量数据。 在models文件里 from django.db import models # Create your models here. class...

python绘图库Matplotlib的安装

python绘图库Matplotlib的安装

本文简单介绍了Python绘图库Matplotlib的安装,简介如下: matplotlib是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地...

pandas dataframe添加表格框线输出的方法

pandas dataframe添加表格框线输出的方法

将dataframe添加到texttable里面,实现格式化输出。 data=[{"name":"Amay","age":20,"result":80}, {"name":"T...

python以环状形式组合排列图片并输出的方法

本文实例讲述了python以环状形式组合排列图片并输出的方法。分享给大家供大家参考。具体分析如下: 这段代码可以自定义一个空白画板,然后将指定的图片以圆环状的方式排列起来,用到了pil库...

python3.0 模拟用户登录,三次错误锁定的实例

python3.0 模拟用户登录,三次错误锁定的实例 实例如下所示: # -*- coding:utf-8 -*- #需求模拟用户登录,超过三次错误锁定不允许登陆 count...