How to plot data against specific dates on the X-axis using Matplotlib?

To plot data against specific dates on the X-axis using matplotlib, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.

  • Make a list of dates and convert them in datetime format as x.

  • Make a list of y data points.

  • Set the formatter of the major ticker.

  • Set the locator of the major ticker.

  • Plot x and y data points using plot() method.

  • To display the figure, use show() method.


from datetime import datetime
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/2021", "01/03/2021", "01/04/2021", "01/05/2021", "01/06/2021", ]

x = [datetime.strptime(d, "%m/%d/%Y").date() for d in dates]
y = [1, 5, 3, 8, 4]

ax = plt.gca()
ax.plot(x, y)


Updated on: 03-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started