pyplot 轴中日期时间的格式

Format of datetime in pyplot axis

我正在尝试使用 pyplot 在 x 轴上针对 datetime 对象列表绘制一些数据。但是,日期显示为标准格式,即 %Y-%m-%d %H:%M:%S(太长了)。我可以通过使用 strftime 创建日期字符串列表并改用它来规避此问题。我也知道 pyplot 有某种 date 内在对象,我可以使用它来代替 datetime.

有没有办法告诉 pyplot 以哪种格式绘制 datetime 对象?无需将所有内容转换为字符串或其他类型的对象?

谢谢。

您可以使用 DateFormatter:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(your_dates, your_data)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

除了如 , you may use rcParams 所示手动指定轴的日期时间格式以设置格式。

标准是

# date.autoformatter.year     : %Y
# date.autoformatter.month    : %Y-%m
# date.autoformatter.day      : %Y-%m-%d
# date.autoformatter.hour     : %m-%d %H
# date.autoformatter.minute   : %d %H:%M
# date.autoformatter.second   : %H:%M:%S
# date.autoformatter.microsecond   : %M:%S.%f

您可以在 matplotlib rc file
中更改 或通过

在代码中
plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S"