Geosphere
Geosphere

Reputation: 375

Format date/time in line plot

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

Upvotes: 1

Views: 737

Answers (2)

Geosphere
Geosphere

Reputation: 375

Inspired by the answer above, I found a way to adjust the formatting as well as the frequency of x-ticks for a line plot when dealing with time series.

ax.xaxis.set_major_locator(md.HourLocator(interval=8))
ax.xaxis.set_major_formatter(
    md.DateFormatter("%Y-%d-%m %H:%M")
)
ax.set_xlim(pd.Timestamp('2022-06-03 16:00:00'), pd.Timestamp('2022-06-06 10:00:00'))

For example the piece of code above helps you set how often you'd like your ticks to show up e.g. every 8 hour. The formatter used in this case will plot the date in short form (yyyy/mm/dd) and the hour and minute.

Upvotes: 0

Laurent
Laurent

Reputation: 13468

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

Upvotes: 1

Related Questions