【问题标题】:Convert x-axis from days to month in matplotlib在 matplotlib 中将 x 轴从天转换为月
【发布时间】:2020-10-03 05:59:28
【问题描述】:

我有 x 轴,它以天为单位(2 月的 366 天被视为 29 天),但我想将其转换为月份(1 月 - 12 月)。我该怎么办...

def plotGraph():
    line, point = getXY()
    
    plt.plot(line['xlMax'], c='orangered', alpha=0.5, label = 'Minimum Temperature (2005-14)')
    plt.plot(line['xlMin'], c='dodgerblue', alpha=0.5, label = 'Minimum Temperature (2005-14)')
    
    plt.scatter(point['xsMax'].index, point['xsMax'], s = 10, c = 'maroon', label = 'Record Break Minimum (2015)')
    plt.scatter(point['xsMin'].index, point['xsMin'], s = 10, c = 'midnightblue', label = 'Record Break Maximum (2015)')
    
    ax1 = plt.gca() # Primary axes
    
    ax1.fill_between(line['xlMax'].index , line['xlMax'], line['xlMin'], facecolor='lightgray', alpha=0.25)
     
    ax1.grid(True, alpha = 1)
    
    for spine in ax1.spines:
        ax1.spines[spine].set_visible(False)
        
    ax1.spines['bottom'].set_visible(True)
    ax1.spines['bottom'].set_alpha(0.3)
    
    # Removing Ticks
    ax1.tick_params(axis=u'both', which=u'both',length=0)
    
    plt.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我认为最快的改变可能是在月初设置新的刻度和刻度标签;我发现了从年份到月份的转换here, the first table

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    x = range(1,367)
    y = np.random.rand(len(range(1,367)))
    
    ax.plot(x,y)
    
    month_starts = [1,32,61,92,122,153,183,214,245,275,306,336]
    month_names = ['Jan','Feb','Mar','Apr','May','Jun',
                   'Jul','Aug','Sep','Oct','Nov','Dec'] 
    
    ax.set_xticks(month_starts)
    ax.set_xticklabels(month_names)
    

    请注意,我假设您的日子编号为 1 到 366;如果它们是 0 到 365,您可能需要更改 range

    但我认为通常更好的方法是让你的日子进入某种datetime;这更灵活,通常非常聪明。如果说您的日子不限于一年,那么将天数与月份关联起来会更复杂。

    此示例使用datetime 代替整数。日期直接绘制在 x 轴上,然后使用来自 matplotlib.datesDateFormatterMonthLocator 来适当地格式化轴:

    import datetime as dt
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import numpy as np
    
    start = dt.datetime(2016,1,1)    #there has to be a year given, even if it isn't plotted
    new_dates = [start + dt.timedelta(days=i) for i in range(366)]
    
    fig, ax = plt.subplots()
    
    x = new_dates
    y = np.random.rand(len(range(1,367)))
    
    xfmt = mdates.DateFormatter('%b')
    months = mdates.MonthLocator()
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(xfmt)
    
    ax.plot(x,y)
    

    【讨论】:

    • 这绝对有效...我会等待更好的方法,如果我没有得到,我会假设没有其他方法并选择您的答案。谢谢大佬!!
    • 查看我的编辑!添加了我认为最好的方法
    • 这种方法是我一直在寻找的,再次感谢!! (b ᵔ▽ᵔ)b
    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多