Python中的matplotlib条件背景颜色

6

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

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,则该日期的背景应为红色。
首先需要添加一个“i”列作为计数器,然后整个代码如下所示,这是我最初想到的使用axvline的解决方法,但是@jakevdp的答案正是我所需的,因为不需要使用循环:
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)

enter image description here


什么的背景颜色?图表?文本标签?数据点本身的颜色?请举个例子。 - MattDMo
图表的背景颜色。想用竖线来完成,但不确定是否是最有效的方法。 - Gabriel
1个回答

14

您可以使用绘图命令,然后跟随pcolor()pcolorfast()。例如,使用上述定义的数据:

ax = df['A'].plot()
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              df['B'].values[np.newaxis],
              cmap='RdYlGn', alpha=0.3)

输入图片描述


可能还需要使用负 z-order。 - tacaswell
2
我想补充一点,当您将具有不同时间轴的不同数据框绘制到一个轴上时,这种方法是不正确的。 - Fred S
我现在无法以最小的工作示例来重现这个问题... 但是问题依然存在,当我在同一个轴上绘制两个具有不同长度和频率的时间序列时,它会绘制出无意义的图形。 - Fred S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接