Home > OS >  Fill vertical areas with datetime xaxis matplotlib
Fill vertical areas with datetime xaxis matplotlib

Time:12-03

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

CodePudding user response:

You can use the where parameter of enter image description here

  • Related