Home > Backend Development > Python Tutorial > How Do I Plot Timestamps on the x-axis in Matplotlib?

How Do I Plot Timestamps on the x-axis in Matplotlib?

Susan Sarandon
Release: 2024-11-30 22:12:15
Original
185 people have browsed it

How Do I Plot Timestamps on the x-axis in Matplotlib?

Plotting Timestamps on the x-Axis in Matplotlib

When plotting data with dates or timestamps on the x-axis, it's important to convert the timestamps to a format that Matplotlib can understand.

In the provided example, the timestamps are in the format (HH:MM:SS.mmmmmm). To plot these timestamps on the x-axis, you need to first convert them to Python datetime objects using the datetime.strptime function.

import datetime

timestamp = '12:00:00.123456'
datetime_object = datetime.strptime(timestamp, '%H:%M:%S.%f')
Copy after login

Once the timestamps are in datetime objects, you can convert them to Matplotlib's date format using the date2num function from the matplotlib.dates module.

import matplotlib.dates

dates = matplotlib.dates.date2num(x_values)
Copy after login

Finally, you can use plot_date to plot the dates and corresponding values.

import matplotlib.pyplot as plt

plt.plot_date(dates, y_values)
plt.show()
Copy after login

This will generate a plot with the dates on the x-axis and the corresponding values on the y-axis.

Note: In Matplotlib version 3.5 and later, plot_date is discouraged. Instead, you should plot datetime data directly using plot and set the x-axis to date format using ax.xaxis.axis_date.

The above is the detailed content of How Do I Plot Timestamps on the x-axis in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template