1

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Geosphere
  • 315
  • 4
  • 15

2 Answers2

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

Laurent
  • 12,287
  • 7
  • 21
  • 37
  • Do you know how could I adjust the frequency, using this method it would plot too many ticks and labels rendering it unreadable. – Geosphere Jun 06 '22 at 08:44
  • I found a way thanks to this post: https://stackoverflow.com/questions/25538520/change-tick-frequency-on-x-time-not-number-frequency-in-matplotlib – Geosphere Jun 06 '22 at 09:03
0

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.

Geosphere
  • 315
  • 4
  • 15