如何在matplotlib中的x轴上显示日期和时间 [英] How to show date and time on x axis in matplotlib
问题描述
我想为matplotlib中的x轴分配随着时间变化的完整日期,但是使用自动缩放,我只能获取时间或日期,而不能同时获取两者.以下代码:
I would like to assign for x axis in matplotlib plot full date with time but with autoscale I could get only times or dates but not both. Following code:
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轴上,我只得到没有任何日期的时间,因此很难区分测量结果.
And on x axis I get only times without any dates so it's hard to distinct measurements.
我认为这是matplotlib.dates.AutoDateFormatter中matplotlib的某些选项,但我找不到任何可以让我更改自动缩放比例的选项.
I think that it's some option in matplotlib in matplotlib.dates.AutoDateFormatter but I couldn't find any one that could allow me to change that autoscale.
推荐答案
您可以使用 matplotlib.dates.DateFormatter
,它以 strftime
格式字符串作为参数.要获取day-month-year hour:minute
格式,可以使用%d-%m-%y %H:%M
:
You can do this with a matplotlib.dates.DateFormatter
, which takes a strftime
format string as its argument. To get a day-month-year hour:minute
format, you can use %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()
这篇关于如何在matplotlib中的x轴上显示日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!