'Format date/time in line plot - matplotlib

I'm having some trouble formatting the x-axis label. I'd like to format the label to show the dates to show the hours but also the date in a YYYY-MM-DD.

Code:

df1.plot.line(y='val1', ax=ax1);
df2.plot.line(y='val1', ax=ax2, legend=False);
plt.suptitle('Some plot ' + str(time[0]) + ' - ' + str(time[1]), fontsize=16, y=1);

#ax1.yaxis.grid(False)
#ax2.yaxis.grid(False)
ax1.grid(linestyle='--', linewidth=0.75)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.set_xlabel('Date-Time')
#ax2.xaxis.set_major_locator(md.MonthLocator())
#ax2.xaxis.set_major_formatter(md.DateFormatter('%Y-%m'))
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.grid(linestyle='--', linewidth=0.75)
ax1.legend(bbox_to_anchor=(1.05, 1));
ax2.legend(bbox_to_anchor=(1.05, 1));
ax1.set_title('ClientAB=0');
ax2.set_title('ClientAB=1');

Some Plot

I would like the hours to remain that way but I'd like the Date to change from 16-May to 2022-05-16. I've tried using formatter from mdates but it displayed the year incorrectly like 3226 instead of 2022.

A sample of how the index looks like in my dataframe

Sample



Solution 1:[1]

Although I can't reproduce your plot, here is one way to change x-ticks formatting:

# Toy dataframe
import pandas as pd

df = pd.DataFrame(
    {
        "date_time": [
            "2022-05-15 08:00:00",
            "2022-05-15 11:00:00",
            "2022-05-15 15:00:00",
            "2022-05-15 19:00:00",
        ],
        "val1": [4, 3, 9, 14],
    }
)

df["date_time"] = pd.to_datetime(df["date_time"])
from matplotlib import pyplot as plt

fig, ax = plt.subplots(nrows=1, ncols=1)

ax.plot(df["date_time"], df["val1"])

plt.shpw()

Which outputs:

enter image description here

Now, same code with these additional lines:

ax.set_xticks(ticks=df["date_time"])
ax.set_xticklabels(df["date_time"].apply(lambda x: x.strftime("%H:%M\n%Y-%m-%d")))

And you get:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Laurent