使用 Matplotlib 在 Python 中绘制时间 [英] Plotting time in Python with Matplotlib
问题描述
我有一个格式为 (HH:MM:SS.mmmmmm) 的时间戳数组和另一个浮点数数组,每个数组对应于时间戳数组中的一个值.
我可以使用 Matplotlib 在 x 轴上绘制时间并在 y 轴上绘制数字吗?
我试图这样做,但不知何故它只接受浮点数数组.我怎样才能让它绘制时间?我必须以任何方式修改格式吗?
您必须首先将时间戳转换为 Python datetime
对象(使用 datetime.strptime
).然后使用 date2num
将日期转换为 matplotlib 格式.
使用
I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.
Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?
I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?
You must first convert your timestamps to Python datetime
objects (use datetime.strptime
). Then use date2num
to convert the dates to matplotlib format.
Plot the dates and values using plot_date
:
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)
这篇关于使用 Matplotlib 在 Python 中绘制时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!