2013-12-09 54 views
1

根據DataFrame中的某一列對pandas子圖進行陰影處理的最優雅方式是什麼?Matplotlib axvspan爲大熊貓着色基於列之一的DataFrame subplots

一個簡單的例子:

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) 

結果在下面的情節:

pandas subplots for axvspan

理想情況下,我想的只是Value1Value2用兩條曲線次要情節使用axvspan其中被陰影On(中的值爲1.0)爲陰影且Off不是陰影。

回答

6

你的設置非常好。不過,我認爲你需要直接與matplotlib交互。

如果您設置數據框像這樣(你有什麼話):

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) 

然後你就可以使用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() 

這給了我: toggle plot