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

2024-04-19 19:09:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matplotlib plot full date with time中指定x轴,但使用autoscale,我只能得到时间或日期,但不能同时得到时间和日期。以下代码:

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


Tags: importdatetimeplotmatplotlibas选项with
2条回答

您可以使用^{}来实现这一点,它以^{}格式的字符串作为参数。要获取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()

enter image description here

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

相关问题 更多 >