Home > Net >  Matplotlib won't follow date format set by set_major_formatter or set_minor_formatter for some
Matplotlib won't follow date format set by set_major_formatter or set_minor_formatter for some

Time:07-15

I am using a program to make a plot of a pandas dataframe with date and time on the x axis and a variable on the y axis. I would like the plot to show the date and time for each tick on the x axis in yyyy-mm-dd hh:mm format.

Here is the code that I am using (I have hardcoded a simple dataframe to make this code easily reproducible). The below code displays this figure, which has the date and time format that I want.

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates

df = pd.DataFrame(
    [['2022-01-01 01:01', 5],
    ['2022-01-01 07:01', 10],
    ['2022-01-01 13:01', 15],
    ['2022-01-01 19:01', 10]], columns=['Time', 'Variable'])
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
df.plot(ax=ax)
ax.tick_params(axis='x', labelrotation=45)
plt.show()

If I subtract one minute from each of the times and run the below code, I get this figure, which has a completely different date and time format.

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates

df = pd.DataFrame(
    [['2022-01-01 01:00', 5],
    ['2022-01-01 07:00', 10],
    ['2022-01-01 13:00', 15],
    ['2022-01-01 19:00', 10]], columns=['Time', 'Variable'])
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
df.plot(ax=ax)
ax.tick_params(axis='x', labelrotation=45)
plt.show()

I have changed nothing about the code except subtract one minute from each time, but the formatting of the ticks changes, even though I have used the set_major_formatter and set_minor_formatter methods to specify a format for each tick.

Is there a way to make sure the format for the ticks stays the same regardless of the dataset that is being plotted?

CodePudding user response:

The code below side steps the issue by avoiding the pandas plotting defaults. You get the same x-axis format for all cases.

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates

df = pd.DataFrame(
    [['2022-01-01 01:00', 5 ],
     ['2022-01-01 07:00', 10],
     ['2022-01-01 13:00', 15],
     ['2022-01-01 19:00', 10]], columns=['Time', 'Variable'])

df['Time'] = pd.to_datetime(df['Time'])
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.plot('Time','Variable',data=df)
ax.tick_params(axis='x', labelrotation=45)
  • Related