Changing the formatting of a datetime axis in Matplotlib

MatplotlibServer Side ProgrammingProgramming

To change the formatting of a datetime axis in matplotlib, we can take the following steps−

  • Create a dataframe df using pandas DataFrame with time and speed as keys
  • Create a figure and a set of subplots using subplots() method.
  • Plot the dataframe using plot method, with df's (Step 1) time and speed.
  • To adjust the tick labels, we can rotate tick_params by 45 degrees
  • To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.
  • To display the figure, use show() method.

Example

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, dates
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(dict(time=list(pd.date_range("2021-01-01 12:00:00",
   periods=10)), speed=np.linspace(1, 10, 10)))
fig, ax = plt.subplots()
ax.plot(df.time, df.speed)
plt.tick_params(rotation=45)
ax.xaxis.set_major_formatter(dates.DateFormatter('%y:%m:%d'))
plt.show()

Output

raja
Published on 06-May-2021 13:42:04
Advertisements