2017-05-01 2 views
2

私は、サブプロットを含むパンダプロットで春の月を陰にしようとしています。しかし、それは最後のサブプロットだけを陰影付けしています。すべてのプロットを陰にするにはどうすればいいですか?pandas:すべてのサブプロットにaxvspanを適用する

私はaxvspanを使用して、毎年4月1日から6月30日までの日陰を、これらの終了日のグループ化されたデータフレームを通してループします。

結果は次のとおりです。可能な限りあなたのコードの多くを使用して

pandas subplots

import matplotlib.pyplot as plt 

recent = daily[daily.Date.dt.year >= 2000] 

# Get only April 1 and Jume 30 each year 
spring_months = recent[((recent.Date.dt.month == 4) & (recent.Date.dt.day == 1)) | ((recent.Date.dt.month == 6) & (recent.Date.dt.day == 30))]['Date'] 

# Make pivot table with data, one measuring station per column. 
recent = recent.pivot(index='Date', columns='Station', values = 'Niveau(m)') 

recent.plot(figsize=[7,50], subplots=True) 
plt.xlim(xmax='2017-07-10') 

# Group the spring end-dates by year 
years = spring_months.drop_duplicates().groupby(spring_months.dt.year) 

# Loop through groups and add axvspan between April 1 and June 30 each year 
for n, g in years: 
    plt.axvspan(g.iloc[0], g.iloc[1], facecolor='g', alpha=0.5) 
    if g.iloc[0].year == 2016: 
     break 

答えて

2

、私は偽のデータセットにビットを変更しました。キーはax = df.plot...ステートメントでサブプロットの軸ハンドルをキャプチャすることです。

リストの理解を使ってすべての軸をループし、axvspanを描くことができます。

データセットを作成します。axspans

# Loop through groups and add axvspan between April 1 and June 30 each year 
for n, g in years: 
    [i.axvspan(g.iloc[0], g.iloc[1], facecolor='g', alpha=0.5) for i in ax] 
    if g.iloc[0].year == 2016: 
     break 

enter image description here

を描画するために、リスト内包表記ですべての軸スルー

ax = df.plot(subplots=True, figsize=(6,6)) 


# Group the spring end-dates by year 
years = spring_months.drop_duplicates().groupby(spring_months.dt.year) 

ループ:

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) 
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) 

df1 = df.rename_axis('date').reset_index() 

import matplotlib.pyplot as plt 

recent = df1[df1.date.dt.year >= 2000] 

# Get only April 1 and Jume 30 each year 
spring_months = df1[((df1.date.dt.month == 4) & (df1.date.dt.day == 1)) | ((df1.date.dt.month == 6) & (df1.date.dt.day == 30))]['date'] 

# Make pivot table with data, one measuring station per column. 
#recent = recent.pivot(index='Date', columns='Station', values = 'Niveau(m)') 

は、すべての軸のハンドルを取得します。

+0

それはそれを行い、非常に効率的です。 – robroc

関連する問題