Matplotlib에서 날짜 축을 다룰 때 12개월(1년)마다 연도 눈금이 표시되도록 설정하려면 몇 가지 단계를 거치면 됩니다. 이 글에서는 Pandas, NumPy, 그리고 Matplotlib의 dates 모듈을 활용해 월별 눈금과 연도 눈금을 함께 표시하는 방법을 소개합니다.
구현 단계
- 그림(figure) 크기를 설정하고 서브플롯 주변과 사이의 여백(padding)을 조정합니다.
- Pandas, NumPy, matplotlib.dates 모듈을 사용하여 d, y, s, years, months, monthsFmt, yearsFmt 객체를 생성합니다.
- DateFormatter에 "%B" 형식 코드를 지정하면 월의 전체 이름(January, February 등)이 표시됩니다.
- DateFormatter에 "%Y" 형식 코드를 지정하면 연도가 표시됩니다.
plt.figure()로 새 그림을 생성하거나 기존 그림을 활성화합니다.add_subplot()메서드를 사용해 그림에 축(ax)을 추가합니다.plot()메서드로 "dts"와 "s" 데이터 포인트를 그립니다.- x축의 major/minor 로케이터(locator)와 포매터(formatter)를 설정합니다. minor 로케이터를 months(MonthLocator)로 지정하면 매달 눈금이 생기고, major 로케이터를 years(YearLocator)로 지정하면 12개월마다 연도 눈금이 표시됩니다.
- 마지막으로
show()메서드를 호출해 그림을 화면에 출력합니다.
예제 코드
import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = pd.date_range("2020-01-01", "2021-06-01", freq="7D")
y = np.cumsum(np.random.normal(size=len(d)))
s = pd.Series(y, index=d)
years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%B')
yearsFmt = mdates.DateFormatter('\n%Y')
dts = s.index.to_pydatetime()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dts, s)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
plt.show()
코드 설명
pd.date_range()는 2020년 1월 1일부터 2021년 6월 1일까지 7일 간격의 날짜 인덱스를 생성하고, np.cumsum(np.random.normal(...))은 무작위 데이터를 누적합으로 만들어 시계열 흐름처럼 보이게 합니다. 핵심은 mdates.YearLocator()를 major 로케이터로, mdates.MonthLocator()를 minor 로케이터로 지정하는 부분입니다. 이렇게 하면 매달 월 이름이 세로로 회전된 작은 눈금 레이블로 표시되고, 해가 바뀌는 지점에는 줄바꿈(\n%Y)과 함께 연도가 큰 눈금으로 나타납니다.
실행 결과
위 코드를 실행하면 x축에 매월 이름이 표시되고, 12개월 주기로 연도 눈금이 함께 출력된 그래프를 확인할 수 있습니다.

