Home >Backend Development >Python Tutorial >How to Plot Time on the X-axis Using Matplotlib?

How to Plot Time on the X-axis Using Matplotlib?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 09:26:12210browse

How to Plot Time on the X-axis Using Matplotlib?

Plotting Time on an Independent Axis with Matplotlib

Convert Timestamps to Datetime Objects and Plot Using plot_date()

In order to plot time on the x-axis using Matplotlib, it's necessary to first convert your timestamp arrays to Python datetime objects. Utilize datetime.strptime to complete this conversion.

Subsequently, use date2num to transform the dates into matplotlib format.

Finally, leverage the plot_date function to visualize the dates and their corresponding values.

import matplotlib.pyplot as plt
import matplotlib.dates

from datetime import datetime

# Datetime Objects as Independent Variable
time_strs = ['00:00:00.000000', '01:00:00.000000', '02:00:00.000000']
x_values = [datetime.strptime(t, '%H:%M:%S.%f') for t in time_strs]

# Corresponding y-axis values
y_values = [0.1, 0.2, 0.3]

# Convert dates to matplotlib format
dates = matplotlib.dates.date2num(x_values)

# Plot Time vs. Values
plt.plot_date(dates, y_values)
plt.xlabel('Time')
plt.ylabel('Value')
plt.show()

This code will effectively plot time as the independent variable on the x-axis, with the corresponding y-axis values being represented.

The above is the detailed content of How to Plot Time on the X-axis Using Matplotlib?. 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