0

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

3
  • 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)). With x being an integer or a weekday constant, as shown here. Commented Mar 9, 2021 at 10:12
  • 1
    In your example, you could set x in my previous comment like this byweekday=date_df.ts[0].weekday(). Commented Mar 9, 2021 at 10:21
  • Yes, it worked with this thank yo so much Commented Mar 11, 2021 at 20:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.