在我的matplotlib图中,datetime x轴当前的格式为
ax.xaxis.set_major_locator(dt.MonthLocator())
ax.xaxis.set_major_formatter(dt.DateFormatter('%d %b'))
ax.xaxis.set_minor_locator(dt.DayLocator())
ax.xaxis.set_minor_formatter(ticker.NullFormatter())
我想要有小刻度的标签,但只有一些值。期望值:
我应该使用什么minor_formatter
?
发布于 2019-06-25 05:14:48
次要刻度需要有选择性标签-仅在具有特定值的日期显示。为了选择日期,我想出了我自己的格式化程序,它接受一个谓词(传递datetime时返回true/false的函数)包装一个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
...
https://stackoverflow.com/questions/56088566
复制相似问题