【问题标题】:Format of datetime in pyplot axispyplot 轴中日期时间的格式
【发布时间】:2015-07-10 05:02:23
【问题描述】:

我正在尝试使用 pyplot 针对 x 轴上的 datetime 对象列表绘制一些数据。然而,日期显示为标准格式,即%Y-%m-%d %H:%M:%S(太长了)。我可以通过使用strftime 创建日期字符串列表来规避这个问题,然后改用它。我也知道pyplot 有某种date 固有对象,我可以使用它来代替datetime

有没有办法告诉pyplot 以哪种格式绘制datetimeobjects?无需将所有内容转换为字符串或其他类型的对象?

谢谢。

【问题讨论】:

    标签: python datetime matplotlib


    【解决方案1】:

    你可以使用DateFormatter:

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(your_dates, your_data)
    
    # format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
    import matplotlib.dates as mdates
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    
    # rotate and align the tick labels so they look better
    fig.autofmt_xdate()
    

    【讨论】:

      【解决方案2】:

      除了手动指定坐标轴的日期时间格式,如the other answer 所示,您还可以使用rcParams 设置格式。

      标准是

      # date.autoformatter.year     : %Y
      # date.autoformatter.month    : %Y-%m
      # date.autoformatter.day      : %Y-%m-%d
      # date.autoformatter.hour     : %m-%d %H
      # date.autoformatter.minute   : %d %H:%M
      # date.autoformatter.second   : %H:%M:%S
      # date.autoformatter.microsecond   : %M:%S.%f
      

      您可以在matplotlib rc file 中更改它,
      或在代码中通过

      plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S"
      

      【讨论】:

      • 与否决票可能暗示的不同,此方法运行良好,与其他选项相比,甚至可以节省一些输入。
      • 我同意,这完全可以解决问题。
      • date.autoformatter使用的库是什么?
      猜你喜欢
      • 2020-02-02
      • 2020-12-07
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多