matplotlib.dates 모듈을 사용한 날짜 수정
import matplotlib.pyplot as plt import matplotlib.dates as mpl_dates
형식: mpl_dates.DateFormatter('%y%m%d')
- '%Y-%m-%d': YYYY-MM-DD 형식
- '%Y/%m/%d': YYYY/MM/DD 형식
- '%b %d, %Y': Apr 15, 2025 형식
- '%y-%m-%d %H:%M:%S': yy-mm-dd HH:MM:SS 형식
축의 눈금 간격을 조정하기 위해 이 모듈이 Locator 클레스를 함께 사용합니다.
- DayLocator(): 특정 일 간격으로 눈금을 표시합니다.
- WeekdayLocator(): 특정 요일마다 눈금을 표시합니다.
- MonthLocator(): 특정 월마다 눈금을 표시합니다.
- YearLocator(): 특정 연도마다 눈금을 표시합니다.
- AutoDateLocator(): 자동으로 최적의 눈금 간격을 설정합니다.
다음은 일정기간의 주가 data에 대해 그래프를 작성한 것으로 x축을 날짜 표시를 첨가한 것입니다.
plt.figure(figsize=(6, 3)) plt.plot(df["Close"]) ax=plt.gca() ax.xaxis.set_major_locator(mpl_dates.AutoDateLocator()) ax.xaxis.set_major_formatter(mpl_dates.DateFormatter('%y/%m/%d')) plt.xticks(rotation=45) plt.show()
gac() 함수는 현재 활성화된 Axes 객체를 반환합니다. 즉, 그래프내의 데이터를 플롯하는 영역을 나타냅니다. 그러므로 ax=plt.gca()는 작성된 플롯의 축 객체를 ax에 할당한 것으로 ax.xaxis.~()는 그 풀롯의 x축을 조정하기 위해 작성한 것입니다.
gci()는 현재 활성화된 Image 객체를 반환합니다. Image 객체는 plt.imshow() 등을 사용하여 플롯된 이미지 데이터를 의미합니다.
다음 코드는 두개의 subplot에서 x축을 공유하면서 tick의 간격을 고정시키고 날짜 형식을 특정하게 지정하기 위한 것입니다.
locator = mpl_dates.DayLocator(interval=20) formatter = mpl_dates.DateFormatter('%y/%m/%d') &vellips; axs[0].xaxis.set_major_locator(locator) axs[0].xaxis.set_major_formatter(formatter) axs[0].set_xticklabels([]) &vellips; axs[1].xaxis.set_major_locator(locator) axs[1].xaxis.set_major_formatter(formatter) plt.xticks(rotation=45) &vellips;
댓글
댓글 쓰기