簡體   English   中英

用日期時間填充垂直區域 xaxis matplotlib

[英]Fill vertical areas with datetime xaxis matplotlib

我嘗試在某些年份填充垂直區域。 理想情況下,我想在 2000 年 1 月至 2000 年 5 月、2003 年 12 月至 2004 年 5 月、2004 年 12 月至 2005 年 5 月、2010 年、2016 年和 2020 年的位置垂直灰色區域。但是,我必須手動進行需要很長時間,可能無法更正我想要的 position。 我在這里附上我制作的示例代碼,希望得到更好的解決方案。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import pandas as pd
# Create some random data
df=pd.DataFrame({"value":np.random.randint(0,100,263),"time":pd.date_range("2000-01-01","2021-11-01",freq="MS")})
# Make plot
fig, ax=plt.subplots(nrows=1,ncols=1, figsize=(15,12))
ax.plot(df.time,df.value)
ax.xaxis.set_major_locator(mdates.YearLocator(2))
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(2))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
# Fill some years with gray area
ax.axvspan(10957, 11200, ymin=0.01, ymax=0.98, alpha=0.7, color='gray')

您可以使用fill_betweenwhere參數和混合轉換

ax.fill_between(df.time, .98, .01, 
                where=df.time.dt.month.le(5) | df.time.dt.month.eq(12),
                color='gray', alpha=0.7, transform=ax.get_xaxis_transform())

在此處輸入圖像描述

暫無
暫無

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

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