【问题标题】:Matplotlib date manipulation so that the year tick show up every 12 monthsMatplotlib 日期操作,以便每 12 个月显示一次年份刻度
【发布时间】:2016-02-14 21:41:18
【问题描述】:

我正在绘制一个默认格式显示为的图形:

我想修改它,使月份刻度每 1 个月显示一次,但保留年份。我目前的尝试是这样的:

years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%b-%y')
dts = s.index.to_pydatetime()

fig = plt.figure(); ax = fig.add_subplot(111)
ax.plot(dts, s)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)

但它没有产生正确的结果:

我究竟需要如何修改它以使其像第一个一样显示,但每个月都会出现月份刻度?

【问题讨论】:

    标签: python date matplotlib


    【解决方案1】:

    想出了一个解决方案,即在次要刻度中保留几个月,并在主要刻度中保留几年。

    例如

    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)
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多