Home >Backend Development >Python Tutorial >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:
import matplotlib.pyplot as plt import matplotlib.dates from datetime import datetime
x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
dates = matplotlib.dates.date2num(x_values)
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!