簡體   English   中英

pandas:將axvspan應用於所有子圖

[英]pandas: apply axvspan to all subplots

我試圖用一個子圖來遮蔽大熊貓情節中的春季。 但它只是遮蔽最后一個子情節。 如何讓它遮蓋所有陰影?

我使用axvspan在每年的4月1日到6月30日之間通過循環這些結束日期的分組數據axvspan來進行遮蔽。

這是結果。

大熊貓子圖

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

使用盡可能多的代碼,我修改了一點來偽造數據集。 關鍵是使用ax = df.plot...語句捕獲子圖的軸控制柄。

然后你可以使用列表推導來遍歷所有的軸並繪制axvspan。

創建數據集:

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)')

獲取所有軸的手柄:

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)

通過列表理解循環所有軸以繪制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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM