【问题标题】:Change xtick labels from pandas plot to different date format将熊猫图中的 xtick 标签更改为不同的日期格式
【发布时间】:2020-06-19 20:34:56
【问题描述】:

我从这个数据框中绘制数据。

Date    2011    2012    2013    2014    2015    2016    2017    2018    2019    2020
Date                                        
01-01   12.896  13.353  12.959  13.011  13.073  12.721  12.643  12.484  12.876  13.102
01-02   12.915  13.421  12.961  13.103  13.125  12.806  12.644  12.600  12.956  13.075
01-03   12.926  13.379  13.012  13.116  13.112  12.790  12.713  12.634  12.959  13.176
01-04   13.051  13.414  13.045  13.219  13.051  12.829  12.954  12.724  13.047  13.187
01-05   13.176  13.417  13.065  13.148  13.115  12.874  12.956  12.834  13.098  13.123

该图会在一年中的每一天为每一年生成一个折线图。

ice_data.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=4, fontsize=16, ax=ax, grid=True)

但是,此图从 01-01(1 月 1 日)的数据帧中生成格式为 xtick 标签。我想将 xtick 标签更改为 01 Jan,但似乎无法弄清楚如何使用 strftime() 操作数据框来完成此操作。这是一张供参考的图片。

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    通过to_datetime 将值转换为日期时间并指定年份以正确解析2-29,最后通过DatetimeIndex.strftime 转换为自定义格式:

    idx = pd.to_datetime('2000' + ice_data.index, format='%Y%m-%d').strftime('%d %b')
    ice_data = ice_data.set_index(idx)
    

    【讨论】:

    • 我收到此错误:ValueError: day is out of range for month
    • @EliTurasky - 你现在可以检查吗?也许2-29 有问题。
    • 是的,这就是问题所在。谢谢!
    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多