所以我找到了一些例子,我调整了我的x轴只是我想要的一个案例。
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as dates
def my_format_function(x, pos=None):
x = dates.num2date(x)
if pos == 0:
fmt = '%H:%M\n%d-%b-%Y'
else:
fmt = '%H:%M'
label = x.strftime(fmt)
return label
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(250)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.figure(figsize=(10,10), facecolor='white', edgecolor='black')
plt.plot(x,y)
x_axis = plt.gca().get_xaxis()
x_axis.set_major_locator(dates.HourLocator())
x_axis.set_major_formatter(dates.ticker.FuncFormatter(my_format_function))
x_axis.set_minor_locator(dates.MinuteLocator(byminute=range(15,60,15)))
x_axis.set_minor_formatter(dates.DateFormatter(':%M'))
x_axis.set_tick_params(which='major', labelsize=10)
x_axis.set_tick_params(which='minor', pad=4, labelsize=8, labelcolor='#333333')
plt.grid(which = 'minor', alpha = 0.4)
plt.grid(which = 'major', alpha = 0.9)
plt.show()
Example plot for x_axis formatting datetime
我最近看到了一些例子,但是我无法跟进,其中AutoDateFormatter与一些规则一起使用以适应不同的时间等等。我可以使用一些帮助。以下是我要开始制定的规则,并了解它的用途。
Example x_axis rules for formatting datetime
更新: 经过一番严肃的挖掘后,我能够达到我想要的效果,但我觉得它的编码非常糟糕。我将能够将def推送到一个单独的文件中进行清理。我愿意接受一些严谨的建议来修剪和清洁。我仍然需要捕获时间<1秒的方法以及时间> 1天。
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 01 15:31:31 2016
@author: Frank
"""
import numpy as np
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as dates
def formatterMinorMicroSeconds(x,pos=None):
x = dates.num2date(x)
label = x.strftime('%S.')+str(int(x.microsecond/1000))+'s'
return label
def formatterMajorSeconds(x, pos=None):
x = dates.num2date(x)
if (non_crossing_minute==True and pos == 0) or (non_crossing_minute ==False and x.second == 0):
fmt = '\n%H:%M:%S\n%d-%b-%Y'
else:
fmt = ''
label = x.strftime(fmt)
return label
def formatterMajorMinutes(x, pos=None):
x = dates.num2date(x)
if (non_crossing_hour==True and pos == 0) or (non_crossing_hour == False and x.minute == 0):
fmt = '\n%H:%M\n%d-%b-%Y'
else:
fmt = '\n%H:%M'
label = x.strftime(fmt)
return label
datetime.datetime.strftime()
def formatterMajorHours(x, pos=None):
x = dates.num2date(x)
if (non_crossing_day==True and pos == 0) or (non_crossing_day == False and x.hour == 0):
fmt = '\n%H:%M\n%d-%b-%Y'
else:
fmt = '\n%H:%M'
label = x.strftime(fmt)
return label
datetime.datetime.strftime()
def dynamicDateLocator(x):
global non_crossing_minute, non_crossing_hour, non_crossing_day
#establish the time boundaries
start_time = x.min()
stop_time = x.max()
# establish time delta for plot duration hours, seconds, microseconds
time_delta = stop_time - start_time
if time_delta.days == 0:
# first determine if the plot crosses from one minute to the next
if time_delta.seconds + start_time.second < 60:
non_crossing_minute = True
else:
non_crossing_minute = False
if time_delta.seconds/60 + start_time.minute < 60:
non_crossing_hour = True
else:
non_crossing_hour = False
if time_delta.seconds/3600 + start_time.hour < 24:
non_crossing_day = True
else:
non_crossing_day = False
# format major and minor scaling based on how large the time scale is
if time_delta.seconds < 2: # 2 seconds
return dates.SecondLocator(bysecond=range(0,60,1)),dates.ticker.FuncFormatter(formatterMajorSeconds), \
dates.MicrosecondLocator(interval=200000),dates.ticker.FuncFormatter(formatterMinorMicroSeconds)
elif time_delta.seconds < 30: # 30 seconds
return dates.SecondLocator(bysecond=range(0,60,5)),dates.ticker.FuncFormatter(formatterMajorSeconds), \
dates.MicrosecondLocator(interval=1000000),dates.DateFormatter('%Ss')
elif time_delta.seconds < 60: # 1 minute
return dates.SecondLocator(bysecond=range(0,60,20)),dates.ticker.FuncFormatter(formatterMajorSeconds), \
dates.MicrosecondLocator(interval=5000000),dates.DateFormatter('%Ss')
elif time_delta.seconds < 60*5: # 5 minutes
return dates.MinuteLocator(byminute=range(0,60,1)),dates.ticker.FuncFormatter(formatterMajorMinutes), \
dates.SecondLocator(bysecond=range(0,60,15)),dates.DateFormatter('%Ss')
elif time_delta.seconds < 60*30: # 30 minutes
return dates.MinuteLocator(byminute=range(0,60,5)),dates.ticker.FuncFormatter(formatterMajorMinutes), \
dates.MinuteLocator(byminute=range(0,60,1)),dates.DateFormatter('%Mm')
elif time_delta.seconds < 60*60: # 60 minutes
return dates.MinuteLocator(byminute=range(0,60,10)),dates.ticker.FuncFormatter(formatterMajorMinutes), \
dates.MinuteLocator(byminute=range(0,60,2)),dates.DateFormatter('%Mm')
elif time_delta.seconds < 60*60*10: # 10 hours
return dates.HourLocator(byhour=range(0,60,1)),dates.ticker.FuncFormatter(formatterMajorHours), \
dates.MinuteLocator(byminute=range(0,60,30)),dates.DateFormatter('%Mm')
elif time_delta.seconds < 60*60*24: # 24 hours
return dates.HourLocator(byhour=range(0,60,3)),dates.ticker.FuncFormatter(formatterMajorHours), \
dates.HourLocator(byhour=range(0,60,1)),dates.DateFormatter('%Hh')
# make up some data
x = np.array([datetime.datetime.now() + datetime.timedelta(seconds=i) for i in range(2000)])
y = np.array([i+random.gauss(0,1) for i,_ in enumerate(x)])
# plot
plt.figure(figsize=(12,5), facecolor='white', edgecolor='black')
plt.plot(x,y)
x_axis = plt.gca().get_xaxis()
major_locator,major_formatter,minor_locator,minor_formatter = dynamicDateLocator(x)
x_axis.set_major_locator(major_locator)
x_axis.set_major_formatter(major_formatter)
x_axis.set_minor_locator(minor_locator)
x_axis.set_minor_formatter(minor_formatter)
x_axis.set_tick_params(which='major', labelsize=10)
x_axis.set_tick_params(which='minor', pad=4, labelsize=8, labelcolor='#333333')
plt.grid(which = 'minor', alpha = 0.5)
plt.grid(which = 'major', alpha = 0.9)
plt.show()