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

前端 未结 2 1209
猫巷女王i
猫巷女王i 2020-12-19 19:57

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.

this is what the plot look

相关标签:
2条回答
  • 2020-12-19 20:10

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

    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'))
    

    0 讨论(0)
  • 2020-12-19 20:23

    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.

    min = 15
    ax.xaxis.set_major_locator(MinuteLocator(byminute=range(0,60,min)) )
    ax.xaxis.set_major_formatter( DateFormatter('%H:%M') )
    
    0 讨论(0)
提交回复
热议问题