Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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 looks like without customizing the y-axis formatting.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...