如何根据图表中不存在的变量更改折线图的背景颜色? 例如,如果我有以下数据框:
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)
最佳答案
您可以使用 plot 命令执行此操作,后跟 pcolor()
或 pcolorfast()
.例如,使用您在上面定义的数据:
ax = df['A'].plot()
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
df['B'].values[np.newaxis],
cmap='RdYlGn', alpha=0.3)
关于python - python 中的 matplotlib 条件背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33355811/