【问题标题】:how to plot time on y-axis in '%H:%M' format in matplotlib?如何在 matplotlib 中以 '%H:%M' 格式在 y 轴上绘制时间?
【发布时间】:2016-06-10 09:01:43
【问题描述】:

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

这是没有自定义 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()

在阅读了关于 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()

谁能给我建议?

【问题讨论】:

    标签: python pandas matplotlib python-datetime


    【解决方案1】:

    为此,您需要传递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'))
    

    【讨论】:

    • 导入 pandas 会隐式安装转换器以正确处理 datetime64(通过 pandas dt64 盒装数据类型清洗它们)。
    • 感谢@tcaswell,但在我上面的示例中导入了 pandas (0.17.0)。关于它为什么不起作用的任何建议?
    • @tcaswell 不确定您的意思,我必须添加 .tolist() 调用才能使 HourLocator 工作。我注意到在绘制.df.timematplotlib 时使用 pandas 的东西来表示刻度和标签,但我没有找到一种简单的方法来自定义它们以满足要求。
    【解决方案2】:

    您可以尝试两种方法: 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') )
    

    【讨论】:

    • 谢谢,但这些行似乎不起作用。还有,为什么时间在y轴上时应该是ax.axis?
    猜你喜欢
    • 2021-12-09
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多