Issue
I try to fill vertical areas at certain years. Ideally, I want to vertical gray areas at positions from Jan 2000 to May 2000, from Dec 2003 to May 2004, from Dec 2004-May 2005, the same for 2010, 2016 and 2020. However, I have to do it mannually and it takes very long time and may not correct the position I want. I attached here the sample code I made, and hope receive better solutions.
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')
Solution
You can use the where
parameter of fill_between
and a blended transformation:
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())
Answered By - Stef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.