1

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

Resulting Plot: enter image description here

  • 1
    With `mdates.DayLocator(interval=7)` a tick should land on Feb-02 which is outside of the plot limits. If you would like to keep the same interval but have the ticks starting on the first day of your dataset you can use [`ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=x))`](https://matplotlib.org/stable/api/dates_api.html#matplotlib.dates.WeekdayLocator). With x being an integer or a weekday constant, as shown [here](https://matplotlib.org/stable/api/dates_api.html#date-tickers). – Patrick FitzGerald Mar 09 '21 at 10:12
  • 1
    In your example, you could set x in my previous comment like this `byweekday=date_df.ts[0].weekday()`. – Patrick FitzGerald Mar 09 '21 at 10:21
  • Yes, it worked with this thank yo so much – Ayse Tugba Ozturk Mar 11 '21 at 20:05

0 Answers0