我试图将温度值与时间进行对比,格式为HH:MM。我可以将xticks设置为每15分钟重复一次,但第一次打勾是第一次(例如04:40)。
有没有办法让小时和同时的四分之一小时(04:45,05:00,05:15等)发生嘀嗒声?我目前的代码如下:
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)
答案 0 :(得分:10)
您可以告诉MinuteLocator
仅使用0,15,30,45
参数使用分钟byminute
。
xlocator = md.MinuteLocator(byminute=[0,15,30,45], interval = 1)
答案 1 :(得分:-1)
labels = ['04:45', '05:00', '05:15']
plt.gca().set_xticklabels(labels)
产生,
将时间转移到并发的四分之一小时,
import datetime
list_dt = [ datetime.datetime(2017,2,15,4,40),
datetime.datetime(2017,2,15,4,46),
datetime.datetime(2017,2,15,4,52),
datetime.datetime(2017,2,15,4,58),
datetime.datetime(2017,2,15,5,4),
datetime.datetime(2017,2,15,5,10)]
adjust_list_dt = list()
for dt in list_dt:
print(dt.minute//15)
if dt.minute % 15 == 0:
adjust_minutes = dt.minute
else:
adjust_minutes = (dt.minute//15 + 1)*15
if adjust_minutes == 60:
adjust_list_dt.append(dt.replace(hour=dt.hour+1, minute=0))
else:
adjust_list_dt.append(dt.replace(minute=adjust_minutes))
print(adjust_list_dt)
# Output
'''
[datetime.datetime(2017, 2, 15, 4, 45),
datetime.datetime(2017, 2, 15, 5, 0),
datetime.datetime(2017, 2, 15, 5, 0),
datetime.datetime(2017, 2, 15, 5, 0),
datetime.datetime(2017, 2, 15, 5, 15),
datetime.datetime(2017, 2, 15, 5, 15)]
'''