Categories
Python Answers

How to plot dates on the x-axis with Python’s matplotlib?

Spread the love

Sometimes, we want to plot dates on the x-axis with Python’s matplotlib.

In this article, we’ll look at how to plot dates on the x-axis with Python’s matplotlib.

How to plot dates on the x-axis with Python’s matplotlib?

To plot dates on the x-axis with Python’s matplotlib, we convert the date strings to datetime objects with strptime.

For instance, we write

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = ['01/02/2022','01/03/2022','01/04/2022']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

to convert the date strings in the dates list to datetime objects with strptime and put them in the x list.

Then we call set_major_formatter to DateFormatter to format the dates in the x-axis.

And we call set_major_locator with DayLocator to put the dates on the x-axis in the right location.

Then we call plot to plot iterables x and y.

And we call autofmt_xdate to format the dates with DateFormatter.

Conclusion

To plot dates on the x-axis with Python’s matplotlib, we convert the date strings to datetime objects with strptime.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *