如何在x轴上显示日期和时间

18
我想在matplotlib绘图中为x轴分配完整的日期和时间,但是使用自动缩放功能只能获取时间或日期,而不能同时获取两者。
import matplotlib.pyplot as plt
import pandas as pd

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))
plt.show()

在x轴上,我只得到了时间,没有日期,所以很难区分测量结果。
我认为在matplotlib.dates.AutoDateFormatter中有一些选项,但我找不到任何一个可以让我改变自动缩放的选项。

enter image description here

3个回答

34
你可以使用 matplotlib.dates.DateFormatter 来实现,该函数需要传入一个 strftime 格式字符串作为参数。如果你想要得到一个 day-month-year hour:minute 的格式,你可以使用 %d-%m-%y %H:%M:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))

xfmt = mdates.DateFormatter('%d-%m-%y %H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

在这里输入图片描述


1
如果您为绘图定义了两个y轴,则可能需要在另一个轴对象上调用“xaxis.set_major_formatter(xfmt)”。 - Dom
我们如何增加X轴上日期的数量(显示日期的频率)? - Nihat
@Nihat,你需要更改“定位器”。例如,在这种情况下,我们可以使用ax.xaxis.set_major_locator(mdates.HourLocator(interval=6))来每隔6小时设置一个刻度。请参阅此处的文档以获取不同可用定位器的列表。 - tmdavison

1
plt.figure() 
plt.plot(...)
plt.gcf().autofmt_xdate() plt.show()

2
在代码答案中添加上下文被认为是有用的。 - Haddock-san

0

以下是在日期和时间列不是您的索引列时如何绘制图表。
fig, ax = plt.subplots() ax.plot('docdate', 'count', data=newdf) fig.autofmt_xdate() plt.show()


9
口头解释通常很有帮助。 - con
2
这只是一个非常简化的答案,没有任何实质性的补充。 - Ruli

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