首页 > 解决方案 > 在 matplotlib 中将 x 轴从天转换为月

问题描述

我有 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()

这就是图表的外观

标签: pythonmatplotlib

解决方案


我认为最快的改变可能是在月初设置新的刻度和刻度标签;我在这里找到了从一年中的一天到一个月的转换,第一个表

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 轴上,然后使用DateFormatterand MonthLocatorfrommatplotlib.dates来适当地格式化轴:

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)

在此处输入图像描述


推荐阅读