Pyplot轴上日期时间的格式

26

我正在尝试使用pyplot绘制一些数据,其中x轴是datetime对象的列表。然而,日期以标准格式显示,即%Y-%m-%d %H:%M:%S(太长了)。我可以通过使用strftime创建日期字符串列表,并使用它代替。我还知道pyplot中有一种内在的date对象,我可以使用它来替代datetime

有没有办法告诉pyplot以哪种格式绘制datetime对象呢?而不必将所有内容转换为字符串或另一种对象?

谢谢。

2个回答

39

您可以使用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()

18
除了像其他答案中手动指定坐标轴的日期时间格式之外,您还可以使用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文件中修改,
或通过代码内部进行修改。
plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S"

3
与其所暗示的负面意义不同,这种方法运作良好,且与其他选项相比可以节省一些打字。 - ImportanceOfBeingErnest
我同意,这完全足以解决问题。 - fdetsch
date.autoformatter 库是用来做什么的? - Dimitri Coukos
另一个答案对我没用,这是唯一有效的答案。 - Fred

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接