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
506 views
in Technique[技术] by (71.8m points)

python - Plotting timestamps (hour/minute/seconds) with Matplotlib

I want to plot some timestamps (Year-month-day Hour-Minute-Second format). I am using the following code, however it doesn't show any hour-minute-second information, it shows them as 00-00-00. I double checked my date array, and as you can see from the snippet below, they are not zero.

Do you have any idea about why I am getting 00-00-00's?enter image description here

import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

dates = [dateutil.parser.parse(s) for s in datestrings]
# datestrings = ['2012-02-21 11:28:17.980000', '2012-02-21 12:15:32.453000', '2012-02-21 23:26:23.734000', '2012-02-26 17:42:15.804000']
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation= 80 )
ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates[0:10],plt_data[0:10], "o-")
plt.show()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try zooming in on your graph, you will see the datetimes expand as your x axis scale changes.

plotting unix timestamps in matplotlib

I had a similarly annoying problem when trying to plot heatmaps of positive selection on chromosomes. If I zoomed out too far things would disappear entirely!

edit: This code plots your dates exactly as you give them, but doesn't add ticks in between.

import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

datestrings = ['2012-02-21 11:28:17.980000', '2012-02-21 12:15:32.453000', '2012-02-21 23:26:23.734000', '2012-02-26 17:42:15.804000']
dates = [dateutil.parser.parse(s) for s in datestrings]

plt_data = range(5,9)
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 )

ax=plt.gca()
ax.set_xticks(dates)

xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates,plt_data, "o-")
plt.show()

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

...