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 - Matplotlib: xticks every 15 minutes, starting on the hour

I am trying to plot values of temperature against time with the time formatted as HH:MM. I am able to set the xticks to recur every 15 minutes but the first tick is at the first time (e.g. 04:40).

Is there a way to shift the ticks to occur on the hour and on the concurrent quarter-hours (04:45, 05:00, 05:15, etc.)? My current code is as follows:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime as dt

## Dummy times and temperatures
time = [dt.datetime(2017,2,15,4,40),dt.datetime(2017,2,15,4,46),dt.datetime(2017,2,15,4,52),dt.datetime(2017,2,15,4,58),dt.datetime(2017,2,15,5,4),dt.datetime(2017,2,15,5,10)]
temp = [7, 8, 9, 10, 11, 12]

## Plot the data
figtemp, ax = plt.subplots(1, 1)
ax.plot(time, temp)

## Set time format and the interval of ticks (every 15 minutes)
xformatter = md.DateFormatter('%H:%M')
xlocator = md.MinuteLocator(interval = 15)

## Set xtick labels to appear every 15 minutes
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as HH:MM
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could tell the MinuteLocator to only use the minutes 0,15,30,45 using the byminute argument.

xlocator = md.MinuteLocator(byminute=[0,15,30,45], interval = 1)

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

...