[英]pandas: apply axvspan to all subplots
I'm trying to shade the spring months in a pandas plot with subplots. 我试图用一个子图来遮蔽大熊猫情节中的春季。 But it's only shading the last subplot.
但它只是遮蔽最后一个子情节。 How do I get it to shade all the plots?
如何让它遮盖所有阴影?
I'm using axvspan
to shade between April 1 and June 30 each year by looping through a grouped dataframe of those end-dates. 我使用
axvspan
在每年的4月1日到6月30日之间通过循环这些结束日期的分组数据axvspan
来进行遮蔽。
Here's the result. 这是结果。
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
Using as much of your code as possible, I modified a bit to fake a dataset. 使用尽可能多的代码,我修改了一点来伪造数据集。 The key is to capture the axes handles of the subplot with the
ax = df.plot...
statement. 关键是使用
ax = df.plot...
语句捕获子图的轴控制柄。
Then you can use list comprehension to loop through all the axes and draw the axvspan. 然后你可以使用列表推导来遍历所有的轴并绘制axvspan。
Create a dataset: 创建数据集:
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)')
Get the handles for all the axes: 获取所有轴的手柄:
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)
Loop thru all the axes with list comprehension to draw axspans 通过列表理解循环所有轴以绘制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.