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.