Python에서 datetime 객체로부터 월(month)과 일(day) 정보만 추출하여 그래프의 x축에 표시하려면 Matplotlib의 DateFormatter() 클래스를 활용하면 됩니다. 이 클래스를 사용하면 날짜 데이터를 원하는 형식으로 손쉽게 포매팅할 수 있습니다.
구현 단계
그림(figure) 크기를 설정하고, 서브플롯(subplot) 주변 및 사이의 여백(padding)을 조정합니다.
2차원이며 크기 변경이 가능한 표 형태의 데이터프레임 df를 생성합니다.
그림과 서브플롯 집합을 만듭니다.
plot() 메서드를 사용해 데이터프레임을 그래프로 그립니다.
x축의 포맷터(formatter)를 설정하여 월과 일만 추출해 표시합니다.
show() 메서드를 호출하여 그림을 화면에 출력합니다.
예제 코드
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, dates
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(dict(time=list(pd.date_range("2021-01-01 12:00:00", periods=10)), speed=np.linspace(1, 10, 10)))
fig, ax = plt.subplots()
ax.plot(df.time, df.speed)
ax.xaxis.set_major_formatter(dates.DateFormatter('M:%m\nD:%d'))
plt.show()실행 결과
위 코드를 실행하면 x축에 전체 날짜가 아닌 월(M:%m)과 일(D:%d)만 두 줄로 나뉘어 표시된 그래프가 출력됩니다. DateFormatter에 전달하는 포맷 문자열을 변경하면 연도, 시간 등 다른 요소도 자유롭게 조합하여 표시할 수 있습니다.
