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

相关文章

Python SSL证书验证问题解决方案

Python SSL证书验证问题解决方案

这篇文章主要介绍了Python SSL证书验证问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、SSL问题 1、在你不启...

python字典的常用操作方法小结

Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串、数字、元组等其他容器模型。本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建、访问、删除、...

Python调用adb命令实现对多台设备同时进行reboot的方法

首先,adb实现对设备的reboot命令是:adb reboot . 但是如果是两台/多台设备的时候,需要声明serial number: adb -s serial_no reboot...

由浅入深讲解python中的yield与generator

前言 本文将由浅入深详细介绍yield以及generator,包括以下内容:什么generator,生成generator的方法,generator的特点,generator基础及高级应...

python实现的自动发送消息功能详解

python实现的自动发送消息功能详解

本文实例讲述了python实现的自动发送消息功能。分享给大家供大家参考,具体如下: 一个简单的脚本 #-*- coding:utf-8 -*- from __future__ imp...