【问题标题】:How to convert DOY (Day of year) to months (as text) in a plot?如何在情节中将 DOY(一年中的一天)转换为月份(作为文本)?
【发布时间】:2019-11-27 03:00:42
【问题描述】:

我有每日平均温度、降水量和全球辐射的气候时间序列图。 我生成了这样的图: https://i.ibb.co/w4x2FMN/temp-mean-1999-2018.png

在 x 轴上,我刚刚生成了代表年份 (DOY) 的数字 1 - 365 的列表。

我真正想要的是,x 轴按月份名称(作为字符串)划分,如下所示: https://i.ibb.co/cL2zc87/rplot.jpg

我已经尝试了很多不同的东西,但没有任何效果。

fig = plt.figure(figsize=(10,10))
ax = plt.axes()

x = np.arange(1,366) # here I define the List with DOY
ax.fill_between(x, temp_cum['min'], temp_cum['max'], color='lightgray', label='1999-2017')
#ax.plot(x, merge_table_99_17_without, color='grey', linewidth=0.3)
ax.plot(x, temp_cum['2018'], color='black', label='2018');
ax.legend(loc='upper left')

ax.set_ylabel('daily mean temperature [°C]')
#ax.set_xlabel('DOY')

plt.show()

【问题讨论】:

    标签: python pandas matplotlib plot time-series


    【解决方案1】:

    首先,您应该按照this post 中的说明将数字转换为日期对象。您可以使用以下功能。

    import datetime
    
    def serial_date_to_string(srl_no):
        new_date = datetime.datetime(2018,1,1,0,0) + datetime.timedelta(srl_no - 1)
        return new_date.strftime("%Y-%m-%d")
    

    然后您必须将 x 轴格式化为仅显示月份而不是完整日期。 This post 详细描述了如何执行此操作。

    【讨论】:

    • 第二篇文章终于帮到了我。看看我的其他答案!
    【解决方案2】:

    非常感谢@AUBSieGUL。

    您的第二个链接终于帮助了我:

    import numpy as np
    import matplotlib.pyplot as plt
    import datetime
    import matplotlib.dates as mdates
    
    
    fig = plt.figure(figsize=(12,12))
    ax = plt.axes()
    
    ### I added this!
    # Set the locator
    locator = mdates.MonthLocator()  # every month
    # Specify the format - %b gives us Jan, Feb...
    fmt = mdates.DateFormatter('%b')
    
    numdays = 365
    base = datetime.datetime(2018, 1, 1, 0, 0, 0, 0)
    date_list = [base + datetime.timedelta(days=x) for x in range(0,numdays)]
    ###
    
    ###replaced all x with date_list
    ax.fill_between(date_list, prec_cum['min'], prec_cum['max'], color='lightgray', label='1999-2017')
    ax.plot(date_list, merge_table_99_17_cumsum_without, color='grey', linewidth=0.3)
    ax.plot(date_list, prec_cum['2018'], color='black', label='2018');
    ax.legend(loc='upper left')
    
    ax.set_ylabel('cum. sums of global radiation [kW/m²]')
    #ax.set_xlabel('DOY')
    
    ### I added this!
    X = plt.gca().xaxis
    X.set_major_locator(locator)
    # Specify formatter
    X.set_major_formatter(fmt)
    ###
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 2021-12-10
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      相关资源
      最近更新 更多