Formatting datetime xlabels in matplotlib (pandas df.plot() method)

前端 未结 3 827
南笙
南笙 2020-12-16 19:11

I can\'t figure out how to change the format of these x-labels. Ideally, I\'d like to call strftime(\'%Y-%m-%d\') on them. I\'ve tried things like set_ma

相关标签:
3条回答
  • 2020-12-16 19:32

    The objects in the date_range DF are Timestamp objects. Call Timestamp.strftime on each object:

    date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS')
    date_range = date_range.map(lambda t: t.strftime('%Y-%m-%d'))
    print date_range
    array([2014-01-01, 2014-02-01, 2014-03-01, 2014-04-01, 2014-05-01,
           2014-06-01, 2014-07-01, 2014-08-01, 2014-09-01, 2014-10-01,
           2014-11-01, 2014-12-01, 2015-01-01], dtype=object)
    

    This allows for more general formatting options versus truncating the ticklabel string.

    0 讨论(0)
  • 2020-12-16 19:37

    Simply access the tick labels and change them:

    xtl=[item.get_text()[:10] for item in ax.get_xticklabels()]
    _=ax.set_xticklabels(xtl)
    

    enter image description here

    0 讨论(0)
  • 2020-12-16 19:45

    You could just pass new labels exactly with your preferred strftime:

    ax.set_xticklabels([pandas_datetime.strftime("%Y-%m-%d") for pandas_datetime in df.index])
    

    It's not the prettiest answer, but it gets the job done consistently.

    0 讨论(0)
提交回复
热议问题