I want my x-ticks to show mondays only as Month-Day. I try the solution here I get the the correct tick format however there is something wrong with locator and the first date is not shown correctly. The first tick should be at Feb 03 based on my indexing.
The code to reproduce my results is below:
import seaborn as sns
import matplotlib.dates as mdates
import datetime as dt
import matplotlib.ticker as ticker
import pandas as pd
width, height = plt.figaspect(.30)
fig,ax = plt.subplots(1,1, figsize=(width,height), dpi=300, constrained_layout=False)
day_pal = sns.color_palette("pastel",7)
date_df = pd.DataFrame()
date_df['ts'] = pd.Series(pd.date_range(START_DATE, periods=12*7, freq="D"))
date_df['weekday'] = date_df['ts'].dt.weekday
print(date_df.ts[0])
print(date_df.ts[len(x)-1])
x = list(date_df.ts)
daily_totals = range(len(x)) + np.random.randint(0,10,len(x))
ax.plot(x, daily_totals, lw=3, color='black',alpha=0.5)
plt.axvline(x[42], color="red", lw=5, linestyle="--", alpha = 0.6)
for wkdy in range(0,5):
start = np.array(date_df[date_df.weekday==wkdy]['ts'])
end = start + pd.Timedelta(days=1)
for i in range(len(start)):
ax.axvspan(start[i],end[i],alpha=0.5,color = day_pal[wkdy])
start = np.array(date_df[date_df.weekday==5]['ts'])
end = start + pd.Timedelta(days=2)
for i in range(len(start)):
ax.axvspan(start[i],end[i],alpha=0.5,color = "gray")
ax.set_ylabel("Number of Trips")
ax.set_xlabel("Date")
ax.set_xlim(x[0], x[len(x) -1 ] )
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b-%d"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%b-%d"))
plt.xticks(rotation=65)
plt.show()