python - Pandas :将 axvspan 应用于所有子图

标签 python pandas matplotlib

我正试图在带有子图的 Pandas 图中遮蔽 Spring 月份。但它只是对最后一个子图进行着色。我如何让它遮蔽所有地 block ?

我使用 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

最佳答案

使用尽可能多的代码,我修改了一点以伪造数据集。关键是使用 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)

通过列表理解遍历所有轴以绘制轴跨度

# 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

关于python - Pandas :将 axvspan 应用于所有子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725794/

相关文章:

python - 将 df1 列 1 与 df2 中的所有列进行比较,返回 df2 的索引

Python plot - 堆叠图像切片

python - 如何在networkx中画出更漂亮的树

python-3.x - 通过从目录中读取所有.txt文件来创建一个JSON对象

python - 如何从数据列表制作直方图并使用 matplotlib 绘制它

python - 将列表项映射到带参数的函数

python - 用橙色标记要忽略的属性

python - Python 中有没有一种方法可以检查 os.environ 的条目是变量还是 shell 函数?

python - 将文件保存在特定目录中的常见路径名操作

python - 没有匹配时打印空数据框