次要刻度需要有选择性标签 - 仅在具有特定值的日期显示。为了选择日期,我想出了我自己的格式化程序,它接受一个谓词(函数在传递日期时间时返回真/假),它包装了一个 DateFormatter 来实际格式化字符串。这允许使用更通用的方法(例如,您可以只显示周末)
import matplotlib.dates as dt
import matplotlib.ticker as ticker
class SelectiveDateFormatter(ticker.Formatter):
def __init__(self, predicate, date_formatter, tz=None):
if tz is None:
tz = dt._get_rc_timezone()
self.predicate = predicate
self.dateFormatter = date_formatter
self.tz = tz
def __call__(self, x, pos=0):
if x == 0:
raise 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()')
current_date = dt.num2date(x, self.tz)
should_print = self.predicate(current_date)
if should_print:
return self.dateFormatter(x, pos)
else:
return ""
def set_tzinfo(self, tz):
self.tz = tz
您可以像这样使用它来达到我的示例:
predicate = lambda d: d.day % 10 == 0
format = dt.DateFormatter('%d')
selective_fmt = SelectiveDateFormatter(predicate, format)
ax.xaxis.set_minor_formatter(selective_fmt)
或者只显示周末:
predicate = lambda d: d.weekday() >= 5
...