날짜 틱 로케이터 및 포맷터

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩은 Matplotlib 에서 다양한 날짜 눈금 로케이터 (tick locator) 와 포맷터 (formatter) 를 사용하는 방법에 대한 이해를 제공하는 것을 목표로 합니다. 이 튜토리얼은 시간 기반 데이터를 사용하여 플롯의 X 축을 사용자 정의하기 위해 이러한 함수를 사용하는 방법을 보여줍니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.

학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

필요한 라이브러리 가져오기

이 튜토리얼에 필요한 라이브러리를 가져오는 것으로 시작합니다. matplotlibnumpy를 사용할 것입니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import (
    FR, MO, MONTHLY, SA, SU, TH, TU, WE, AutoDateFormatter, AutoDateLocator,
    ConciseDateFormatter, DateFormatter, DayLocator, HourLocator,
    MicrosecondLocator, MinuteLocator, MonthLocator, RRuleLocator, SecondLocator,
    WeekdayLocator, YearLocator, rrulewrapper)
import matplotlib.ticker as ticker

로케이터 (Locators) 및 포맷터 (Formatters) 정의

사용할 다양한 로케이터와 포맷터를 정의합니다. 이 예제는 다음과 같은 로케이터를 사용합니다.

  • AutoDateLocator(maxticks=8)
  • YearLocator(month=4)
  • MonthLocator(bymonth=[4, 8, 12])
  • DayLocator(interval=180)
  • WeekdayLocator(byweekday=SU, interval=4)
  • HourLocator(byhour=range(0, 24, 6))
  • MinuteLocator(interval=15)
  • SecondLocator(bysecond=(0, 30))
  • MicrosecondLocator(interval=1000)
  • RRuleLocator(rrulewrapper(freq=MONTHLY, byweekday=(MO, TU, WE, TH, FR), bysetpos=-1))

그리고 다음과 같은 포맷터:

  • AutoDateFormatter(ax.xaxis.get_major_locator())
  • ConciseDateFormatter(ax.xaxis.get_major_locator())
  • DateFormatter("%b %Y")
locators = [
    ('AutoDateLocator(maxticks=8)', '2003-02-01', '%Y-%m'),
    ('YearLocator(month=4)', '2003-02-01', '%Y-%m'),
    ('MonthLocator(bymonth=[4, 8, 12])', '2003-02-01', '%Y-%m'),
    ('DayLocator(interval=180)', '2003-02-01', '%Y-%m-%d'),
    ('WeekdayLocator(byweekday=SU, interval=4)', '2000-07-01', '%a %Y-%m-%d'),
    ('HourLocator(byhour=range(0, 24, 6))', '2000-02-04', '%H h'),
    ('MinuteLocator(interval=15)', '2000-02-01 02:00', '%H:%M'),
    ('SecondLocator(bysecond=(0, 30))', '2000-02-01 00:02', '%H:%M:%S'),
    ('MicrosecondLocator(interval=1000)', '2000-02-01 00:00:00.005', '%S.%f'),
    ('RRuleLocator(rrulewrapper(freq=MONTHLY, byweekday=(MO, TU, WE, TH, FR), '
     'bysetpos=-1))', '2000-07-01', '%Y-%m-%d'),
]

formatters = [
    'AutoDateFormatter(ax.xaxis.get_major_locator())',
    'ConciseDateFormatter(ax.xaxis.get_major_locator())',
    'DateFormatter("%b %Y")',
]

그래프 플로팅 (Plotting the Graphs)

이제 그래프를 생성할 수 있습니다. 로케이터와 포맷터를 별도로 시연하기 위해 두 개의 서브플롯 (subplots) 을 생성합니다. 각 로케이터와 포맷터에 대해, X 축에 어떤 영향을 미치는지 보여주는 그래프를 플롯합니다. 이를 위해 plot_axis 함수를 사용합니다. 이 함수는 스파인 (spines), 틱 파라미터 (tick parameters), 제한 (limits) 과 같이 각 축에 대한 공통 매개변수를 설정합니다. 또한 X 축에 대한 로케이터와 포맷터를 설정합니다.

def plot_axis(ax, locator=None, xmax='2002-02-01', fmt=None, formatter=None):
    ax.spines[['left', 'right', 'top']].set_visible(False)
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5)
    ax.set_xlim(np.datetime64('2000-02-01'), np.datetime64(xmax))
    if locator:
        ax.xaxis.set_major_locator(eval(locator))
        ax.xaxis.set_major_formatter(DateFormatter(fmt))
    else:
        ax.xaxis.set_major_formatter(eval(formatter))
    ax.text(0.0, 0.2, locator or formatter, transform=ax.transAxes,
            fontsize=14, fontname='Monospace', color='tab:blue')


fig, axs = plt.subplots(len(locators), 1, figsize=(8, len(locators) * .8),
                        layout='constrained')
fig.suptitle('Date Locators')
for ax, (locator, xmax, fmt) in zip(axs, locators):
    plot_axis(ax, locator, xmax, fmt)

fig, axs = plt.subplots(len(formatters), 1, figsize=(8, len(formatters) * .8),
                        layout='constrained')
fig.suptitle('Date Formatters')
for ax, fmt in zip(axs, formatters):
    plot_axis(ax, formatter=fmt)

그래프 표시

마지막으로, plt.show() 함수를 사용하여 그래프를 표시할 수 있습니다.

plt.show()

요약

이 튜토리얼에서는 Matplotlib 에서 다양한 날짜 틱 로케이터 (tick locators) 와 포맷터 (formatters) 를 사용하는 방법을 배웠습니다. 각 로케이터와 포맷터가 시간 기반 데이터 (time-based data) 가 있는 플롯 (plot) 의 X 축에 어떤 영향을 미치는지 보여주는 여러 그래프를 플롯했습니다. 이 지식은 시계열 데이터 (time series data) 의 시각화를 생성할 때 유용할 수 있습니다.