The code below generates a plot with a properly-labeled x axis. But I don't want the full YYYY-MM-DD HH:MM:SS date format. No problem, a bunch of googling finally turned up the locator / formatter utilities. But if I uncomment the last line with the set_major_formatter
, with no other changes, it formats the date as requested -- but now the x axis starts at the epoch (1970-01-01). !??
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
dates = pd.date_range(start="2021-01-01", end="2022-12-01")
data = [d.day for d in dates]
df = pd.DataFrame(index=dates, columns=[ "Data" ], data=data)
df.plot(kind="bar")
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 4, 7, 10)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
date_form = DateFormatter("%Y-%m")
# ax.xaxis.set_major_formatter(date_form)