简体   繁体   English

Matplotlib axvspan着色为pandas DataFrame子图基于其中一列

[英]Matplotlib axvspan shading for pandas DataFrame subplots based on one of the columns

What is the most elegant way to shade a pandas subplots based on one of the columns in a DataFrame? 根据DataFrame中的一列来遮蔽pandas子图的最优雅方法是什么?

A simple example: 一个简单的例子:

In [8]:
from random import *
import pandas as pd

randBinList = lambda n: [randint(0,1) for b in range(1,n+1)]
rng = pd.date_range('1/1/2011', periods=72, freq='H')
ts = pd.DataFrame({'Value1': randn(len(rng)),'Value2': randn(len(rng)),'OnOff': randBinList(len(rng))}, index=rng)
ts.plot(subplots=True)

Results in the following plot: 结果如下图:

Axvspan的熊猫子图

Ideally, I would like a subplot of just Value1 and Value2 with both plots being shaded using axvspan where On (values with 1.0 in the OnOff ) are shaded and Off is not shaded. 理想情况下,我想要一个只有Value1Value2的子图,两个图都使用axvspan进行着色,其中OnOnOff中的值为1.0 )为阴影, Off为阴影。

You're set up to do this very well. 您已经做好了很好的准备。 I think you'll need to interact with matplotlib directly, however. 我认为您需要直接与matplotlib进行交互。

If you set up your DataFrame like this (what you have already): 如果您是这样设置DataFrame的(已有的):

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

randBinList = lambda n: [np.random.randint(0,2) for b in range(1,n+1)]
rng = pd.date_range('1/1/2011', periods=72, freq='H')
ts = pd.DataFrame({
    'Value1': np.random.randn(len(rng)),
    'Value2': np.random.randn(len(rng)),
    'OnOff': randBinList(len(rng))
}, index=rng)

Then you you can use the fill_between command with the where kwarg: 然后,您可以将fill_between命令与where kwarg一起使用:

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(ts.index, ts['Value1'], 'k-')
ax1.fill_between(ts.index, ts['Value1'], y2=-6, where=ts['OnOff'])

ax2.plot(ts.index, ts['Value2'], 'k-')
ax2.fill_between(ts.index, ts['Value2'], y2=-6, where=ts['OnOff'])
fig.tight_layout()

Which gives me: 这给了我: 切换图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM