如何区分matplotlib的轴是日期还是数字?

时间:2017-04-12 13:21:28

标签: python pandas matplotlib

from matplotlib.dates import AutoDateFormatter
from pandas.tseries.converter import PandasAutoDateFormatter


def _judge_date_axis(axis):
    unit = axis.get_major_formatter()
    return isinstance(unit, AutoDateFormatter) or isinstance(unit, PandasAutoDateFormatter)

这是我的解决方案,有没有更准确和直接的方法? 非常感谢!

1 个答案:

答案 0 :(得分:1)

轴是日期轴的必要但不充分的条件是它附有单位。所以你可以查询

plt.gca().xaxis.have_units()

如果返回False,则不是日期轴。反过来不一定是真的;仅仅因为轴有单位,它不需要是日期。

在您的代码中,您还需要考虑通常的DateFormatter

isinstance(unit, DateFormatter)

也可能是IndexDateFormatter