首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Matplotlib:在x轴上显示选定的日期标签

Matplotlib:在x轴上显示选定的日期标签
EN

Stack Overflow用户
提问于 2019-05-11 08:30:00
回答 1查看 160关注 0票数 2

在我的matplotlib图中,datetime x轴当前的格式为

代码语言:javascript
运行
AI代码解释
复制
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

EN

回答 1

Stack Overflow用户

发布于 2019-06-25 05:14:48

次要刻度需要有选择性标签-仅在具有特定值的日期显示。为了选择日期,我想出了我自己的格式化程序,它接受一个谓词(传递datetime时返回true/false的函数)包装一个DateFormatter来实际格式化字符串。这允许更通用的方法(例如,您可以只显示周末)

代码语言:javascript
运行
AI代码解释
复制
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

您可以像这样使用它来访问我的示例:

代码语言:javascript
运行
AI代码解释
复制
predicate = lambda d: d.day % 10 == 0
format = dt.DateFormatter('%d')
selective_fmt = SelectiveDateFormatter(predicate, format)
ax.xaxis.set_minor_formatter(selective_fmt)

或者只显示周末:

代码语言:javascript
运行
AI代码解释
复制
predicate = lambda d: d.weekday() >= 5
...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56088566

复制
相关文章

相似问题

领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文