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

时间:2015-10-06 14:20:22

标签: python matplotlib

我想在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中的matplotlib中有一些选项,但我找不到任何可以让我更改自动缩放的选项。

enter image description here

3 个答案:

答案 0 :(得分:13)

您可以使用matplotlib.dates.DateFormatter执行此操作,该strftime采用enter image description here格式字符串作为其参数。要获得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()

though not without its pitfalls

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这是在日期和时间列不是您的索引列时绘制日期和时间列的方法。
fig, ax = plt.subplots() ax.plot('docdate', 'count', data=newdf) fig.autofmt_xdate() plt.show()

相关问题