I have a plot where my x-axis is a datetime64 object in a pandas dataframe. Is there a way to somehow identify the day of the week for each date
from matplotlib.dates import MonthLocator, DateFormatter
import matplotlib.dates as mdates
fig1, ax1 = plt.subplots(figsize=(20,8))
ax = plt.plot(time_bookings.ymd, time_bookings.bookings, color="r", marker="o")
plt.grid(axis='x')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.title("Mean daily bookings")
plt.ylabel("Number of Bookings")
plt.xticks(rotation=90)
plt.xlabel("Time (Days)")
ax2 = plt.twiny()
ax2.set_xticks( plot.get_xticks() )
ax2.set_xticklabels(df.weekend)
plt.show()
This is what I've tried but it seems the top label isn't synchronized with the bottom later. The top layer is showing the day of the week Monday being 0 but it appears they are off. March 1 2018 was a thursday.
CodePudding user response:
We can't answer why it shows wrong weekdays when we don't know what is df
in our example. But what about showing the weekends as a step curve in the chart?
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
time_bookings = pd.DataFrame({'ymd': pd.date_range('02/26/2018', '05/03/2018'), 'bookings': np.random.randint(100,200,67)})
fig1, ax1 = plt.subplots(figsize=(20,8))
ax = plt.plot(time_bookings.ymd, time_bookings.bookings, color="r", marker="o")
plt.grid(axis='x')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.title("Mean daily bookings")
plt.ylabel("Number of Bookings")
plt.xticks(rotation=90)
plt.xlabel("Time (Days)")
yl = plt.ylim()
plt.fill_between(time_bookings.ymd,
(time_bookings.ymd.dt.dayofweek >= 5).astype(int) * yl[1],
step='mid',
alpha=.3)
plt.ylim(yl)
plt.show()