How to show date and time on the X-axis in Matplotlib?

PythonServer Side ProgrammingProgramming

To show date and time on the X-axis in Matplotlib, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a list of dates and y values.
  • Get the current axis.
  • Set the major date formatter and locator.
  • Plot x and y values using plot() method.
  • To display the figure, use show() method.

Example

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020", "01/03/2020", "01/04/2020"]
x_values = [dt.strptime(d, "%m/%d/%Y").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

Output

raja
Published on 08-Jul-2021 11:16:44
Advertisements