pandas 如何在matplotlib中以'%H:%M'格式在y轴上绘制时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35663705/
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-09-14 00:46:45  来源:igfitidea点击:

how to plot time on y-axis in '%H:%M' format in matplotlib?

pythonpandasmatplotlibpython-datetime

提问by themachinist

i would like to plot the times from a datetime64 series, where the y-axis is formatted as '%H:%M, showing only 00:00, 01:00, 02:00, etc.

我想绘制 datetime64 系列中的时间,其中 y 轴的格式为 '%H:%M,仅显示 00:00、01:00、02:00 等。

this is what the plot looks like without customizing the y-axis formatting.

这就是没有自定义 y 轴格式的绘图的样子。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.dates import HourLocator

df = pd.DataFrame(data=dict(a=pd.date_range('1/1/2011',periods=1440000,freq='1min')))
df = df.iloc[np.arange(0,1440*100,1440)+np.random.randint(1,300,100)]

plt.plot(df.index,df['a'].dt.time)
plt.show()

enter image description here

在此处输入图片说明

After reading around on the topic on SO, I attempted the following but without success.

在阅读关于 SO 的主题后,我尝试了以下但没有成功。

ax = plt.subplot()
ax.yaxis.set_major_locator(HourLocator())
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
plt.plot(df.index,df['a'].dt.time)
plt.show()

ValueError: DateFormatter found a value of x=0, which is an illegal date.  This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

Could anyone advise me?

有人可以建议我吗?

回答by Stop harming Monica

For that to work you need to pass datetimeobjects (and I mean datetime, not datetime64). You can convert all timestamps to the same date and then use .tolist()to get the actual datetimeobjects.

为此,您需要传递datetime对象(我的意思是datetime,不是datetime64)。您可以将所有时间戳转换为同一日期,然后用于.tolist()获取实际datetime对象。

y = df['a'].apply(lambda x: x.replace(year=1967, month=6, day=25)).tolist()
ax = plt.subplot()
ax.plot(df.index, y)
ax.yaxis.set_major_locator(HourLocator())
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))

enter image description here

在此处输入图片说明

回答by Hun

You can try two things: 1) It should be ax.xaxis.... not ax.yaxis.... 2) Use set_major_locator() instead of set_major_formatter() for Locator. Example is shown below.

您可以尝试两件事:1) 它应该是 ax.xaxis.... 而不是 ax.yaxis.... 2) 使用 set_major_locator() 而不是 set_major_formatter() 作为定位器。示例如下所示。

min = 15
ax.xaxis.set_major_locator(MinuteLocator(byminute=range(0,60,min)) )
ax.xaxis.set_major_formatter( DateFormatter('%H:%M') )