【问题标题】:Setting dates as first letter on x-axis using matplotlib使用 matplotlib 将日期设置为 x 轴上的第一个字母
【发布时间】:2012-03-06 10:30:02
【问题描述】:

我有时间序列图(超过 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')) 

任何帮助将不胜感激。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以下基于官方示例here的sn-p适用于我。

    这使用基于函数的索引格式化程序订单,仅根据请求返回月份的第一个字母。

    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()
    

    【讨论】:

    • 感谢您的回复。我会尝试并回复您!
    【解决方案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】:

      原始答案使用日期索引。这不是必需的。可以改为从 DateFormatter('%b') 获取月份名称,并使用 FuncFormatter 仅使用月份的第一个字母。

      import numpy as np
      import matplotlib.pyplot as plt
      from matplotlib.ticker import FuncFormatter
      from matplotlib.dates import MonthLocator, DateFormatter 
      
      x = np.arange("2019-01-01", "2019-12-31", dtype=np.datetime64)
      y = np.random.rand(len(x))
      
      fig, ax = plt.subplots()
      ax.plot(x,y)
      
      
      month_fmt = DateFormatter('%b')
      def m_fmt(x, pos=None):
          return month_fmt(x)[0]
      
      ax.xaxis.set_major_locator(MonthLocator())
      ax.xaxis.set_major_formatter(FuncFormatter(m_fmt))
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2017-08-23
        • 2022-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 2020-06-09
        相关资源
        最近更新 更多