python chaco 轴标签时间格式化
在Enthought的Chaco库中,TimeFormatter
这个类是用来格式化刻度标签上的时间字符串的。有没有办法可以指定时间格式(类似于time.strftime()
)呢?
现在的源代码在显示月份和日期时,格式是固定的,采用的是美国的格式(MMDD)。我想增加一些灵活性,让时间/日期格式的提示能够传递给TimeFormatter
。
我不知道有什么好的方法可以做到这一点(除了直接修改源代码本身的TimeFormatter._formats
字典)。
1 个回答
4
老实说,最简单的方法就是直接修改 TimeFormatter 的 _formats 字典:
from enthought.chaco.scales.formatters import TimeFormatter
TimeFormatter._formats['days'] = ('%d/%m', '%d%a',)
如果你不想这样做,那你就需要创建一个 TimeFormatter 的子类。这其实很简单。不过,更麻烦的是让 chaco.scales 包里所有现有的比例系统都使用你新创建的子类,而不是内置的 TimeFormatter。如果你查看 scales.time_scale.TimeScale,它在构造函数中接受一个 'formatter' 的参数。所以,在 time_scale.py 的底部,当 MDYScales 列表被创建时,你需要自己创建一个:
EuroMDYScales = [TimeScale(day_of_month=range(1,31,3), formatter=MyFormatter()),
TimeScale(day_of_month=(1,8,15,22), formatter=MyFormatter()),
TimeScale(day_of_month=(1,15), formatter=MyFormatter()),
TimeScale(month_of_year=range(1,13), formatter=MyFormatter()),
TimeScale(month_of_year=range(1,13,3), formatter=MyFormatter()),
TimeScale(month_of_year=(1,7), formatter=MyFormatter()),
TimeScale(month_of_year=(1,), formatter=MyFormatter())]
然后,当你创建 ScalesTickGenerator 时,需要把这些比例传递给 ScaleSystem:
euro_scale_system = CalendarScaleSystem(*(HMSScales + EuroMDYScales))
tick_gen = ScalesTickGenerator(scale=euro_scale_system)
接着你就可以创建坐标轴,并给它这个刻度生成器:
axis = PlotAxis(tick_generator = tick_gen)
希望这些对你有帮助,抱歉回复晚了大约一个月。我其实不太常查看 StackOverflow。如果你还有其他关于 chaco 的问题,建议你加入 chaco-users 邮件列表……