Categories
Python Answers

How to plot time in Python with Matplotlib?

Spread the love

Sometimes, we want to plot time in Python with Matplotlib.

In this article, we’ll look at how to plot time in Python with Matplotlib.

How to plot time in Python with Matplotlib?

To plot time in Python with Matplotlib, we can use datetime objects.

For instance, we write

import matplotlib.pyplot
import matplotlib.dates
from datetime import datetime

x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
y_values = [1.0, 3.0, 2.0]

dates = matplotlib.dates.date2num(x_values)
matplotlib.pyplot.plot_date(dates, y_values)

to add datetime objects into the x_values list.

Then we convert the datetimes to something that we can plot with

dates = matplotlib.dates.date2num(x_values)

And then we write

matplotlib.pyplot.plot_date(dates, y_values)

to plot the values in dates as the values in the x-axis.

Conclusion

To plot time in Python with Matplotlib, we can use datetime objects.

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 *