如何用matplotlib在x轴上绘制时间?

ha5z0ras  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(155)

此问题在此处已有答案

Plotting time on the independent axis(5个答案)
8天前关闭。
按照HERE的例子,我想创建一个在x轴上只显示时间而不是日期的图。所以我修改了示例代码如下:

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.HourLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

字符串
但我得到的不是10:00到10:10的时间范围,而是:


的数据
怎么了?

nukf8bse

nukf8bse1#

我认为有两个问题是,当您将.date()链接到.strptime(...)时,时间信息被丢弃,其次,使用HourLocator而不是MinuteLocator

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M") for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)

#Comment out to show fewer minute ticks
locator = mdates.MinuteLocator()
ax.xaxis.set_major_locator(locator)

plt.plot(x_values, y_values, 'o-');

字符串


的数据

相关问题