【问题标题】:How to convert numpy datetime into the format "MM-DD"如何将 numpy datetime 转换为“MM-DD”格式
【发布时间】:2020-05-04 11:06:18
【问题描述】:

我创建了一个安排来标记包含 2013 年每一天的观察的图表:

dates=np.arange('2013-01-01', '2014-01-01', dtype='datetime64[D]')

它有效,但考虑到所有观察结果均来自同一年(2013 年),我希望标签以 MM-DD 格式呈现。我怎样才能转换它? 图片显示图表,我希望每个标签都是 MM-DD 格式:

【问题讨论】:

    标签: python date matplotlib charts type-conversion


    【解决方案1】:

    这样做:

    from matplotlib.dates import DateFormatter
    
    fig, ax = plt.subplots()
    ax.plot(observation_dates, dfmax.Data_Value) 
    ax.xaxis.set_major_formatter(DateFormatter("%m-%d"))
    

    【讨论】:

    • 我使用以下代码绘制: plt.figure('data') plt.plot(observation_dates, dfmax.Data_Value) plt.show() 如何添加您的代码?
    • 相应地编辑了我的答案
    • 收到此错误消息:“列表”对象没有属性“xaxis”
    • 对不起,我想我搞砸了,试试这个
    【解决方案2】:

    你必须使用matplotlib date formatter

    from matplotlib.dates import DateFormatter
    plt.figure('data')
    plt.plot(dates) # After you plotted your data you can set the formatter
    plt.gca().yaxis.set_major_formatter(DateFormatter("%m-%d")) # plt.gca() gets the     current axes
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2017-05-30
      • 2018-01-08
      相关资源
      最近更新 更多