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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32972371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:33:46  来源:igfitidea点击:

How to show date and time on x axis in matplotlib

pythonmatplotlib

提问by Anton Protopopov

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:

我想在 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()

And on x axis I get only times without any dates so it's hard to distinct measurements.

在 x 轴上,我只得到没有任何日期的时间,因此很难区分测量值。

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

enter image description here

在此处输入图片说明

采纳答案by tmdavison

You can do this with a matplotlib.dates.DateFormatter, which takes a strftimeformat string as its argument. To get a day-month-year hour:minuteformat, you can use %d-%m-%y %H:%M:

您可以使用 a 来执行此操作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()

enter image description here

在此处输入图片说明

回答by Yuchao Jiang

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