Home >Backend Development >Python Tutorial >How to Convert Timestamps to a Matplotlib-Compatible Date Format for X-Axis Plotting?

How to Convert Timestamps to a Matplotlib-Compatible Date Format for X-Axis Plotting?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 22:07:11918browse

How to Convert Timestamps to a Matplotlib-Compatible Date Format for X-Axis Plotting?

Converting Timestamps to Matplotlib Date Format for X-Axis Plotting

In Matplotlib, plotting time data requires specific handling. To plot an array of timestamps on the x-axis while corresponding floating point numbers are on the y-axis, you need to convert the timestamps to Matplotlib's internal date format.

To achieve this conversion, follow the steps below:

  1. Import the necessary libraries:
import matplotlib.pyplot as plt
import matplotlib.dates
from datetime import datetime
  1. Convert the timestamps to datetime objects:
x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
  1. Convert the datetime objects to Matplotlib's date format:
dates = matplotlib.dates.date2num(x_values)
  1. Create the plot using plot_date:
plt.plot_date(dates, y_values)

This will generate a plot where the x-axis represents the timestamps in their formatted date, while the y-axis shows the corresponding floating point numbers.

Note: Matplotlib 3.5 and later versions handle datetime data directly, eliminating the need for the plot_date function. Instead, plot using plot after setting the x-axis data type to dates using ax.xaxis.axis_date.

The above is the detailed content of How to Convert Timestamps to a Matplotlib-Compatible Date Format for X-Axis Plotting?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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