【问题标题】:Matplotlib: Show selected date labels on x axisMatplotlib:在 x 轴上显示选定的日期标签
【发布时间】:2019-09-29 00:14:54
【问题描述】:

在我的 matplotlib 图表中,日期时间 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

【问题讨论】:

    标签: python matplotlib axis-labels


    【解决方案1】:

    次要刻度需要有选择性标签 - 仅在具有特定值的日期显示。为了选择日期,我想出了我自己的格式化程序,它接受一个谓词(函数在传递日期时间时返回真/假),它包装了一个 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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2023-04-05
      相关资源
      最近更新 更多