首页 文章

使用matplotlib将日期设置为x轴上的第一个字母

提问于
浏览
2

我有时间序列图(超过1年),其中x轴上的月份是Jan,Feb,Mar等形式,但我想只有月份的第一个字母(J,F, M等) . 我使用了设置刻度线

ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator())

ax.xaxis.set_major_formatter(matplotlib.ticker.NullFormatter())
ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%b'))

任何帮助,将不胜感激 .

2 回答

  • 2

    我试图让@ Appleman1234建议的解决方案工作,但是因为我,我自己想要创建一个我可以保存在外部配置脚本中并导入其他程序的解决方案,我发现格式化程序必须定义变量是不方便的格式化程序函数本身之外 .

    我没有解决这个问题,但我只是想在这里分享我稍微缩短的解决方案,以便你和其他人可以接受或离开它 .

    事实证明,首先获得标签有点棘手,因为在设置刻度标签之前需要绘制轴 . 否则,只要使用 Text.get_text() ,就会得到空字符串 .

    您可能想要摆脱特定于我的情况的agrument minor=True .

    # ...
    
    # Manipulate tick labels
    plt.draw()
    ax.set_xticklabels(
        [t.get_text()[0] for t in ax.get_xticklabels(minor=True)], minor=True
    )
    

    我希望它有帮助:)

  • 3

    基于官方示例here的以下片段适合我 .

    这使用基于函数的索引格式化程序命令仅返回请求的月份的第一个字母 .

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.mlab as mlab
    import matplotlib.cbook as cbook
    import matplotlib.ticker as ticker
    datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
    print 'loading', datafile
    r = mlab.csv2rec(datafile)
    
    r.sort()
    r = r[-365:]  # get the last year
    
    # next we'll write a custom formatter
    N = len(r)
    ind = np.arange(N)  # the evenly spaced plot indices
    def format_date(x, pos=None):
        thisind = np.clip(int(x+0.5), 0, N-1)
        return r.date[thisind].strftime('%b')[0]
    
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(ind, r.adj_close, 'o-')
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    fig.autofmt_xdate()
    
    plt.show()
    

相关问题