Matplotlib date manipulation so that the year tick show up every 12 months

前端 未结 1 2039
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 21:40

I\'m plotting a figure where the default format shows up as:

I would like to modify it so that the month ticks show up every 1 month but keep the year. My

相关标签:
1条回答
  • 2020-12-16 22:07

    Figured out one solution, which is to stick months into the minor ticks and keep years as the major.

    E.g.

    years = mdates.YearLocator()
    months = mdates.MonthLocator()
    monthsFmt = mdates.DateFormatter('%b') 
    yearsFmt = mdates.DateFormatter('\n\n%Y')  # add some space for the year label
    dts = s.index.to_pydatetime()
    
    fig = plt.figure(); ax = fig.add_subplot(111)
    ax.plot(dts, s)
    ax.xaxis.set_minor_locator(months)
    ax.xaxis.set_minor_formatter(monthsFmt)
    plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    

    Results in:

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