Matplotlib 날짜 눈금 형식 지정

Beginner

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

소개

~.dates.ConciseDateFormatter는 Matplotlib 을 사용할 때 날짜 눈금 (date ticks) 을 형식화하는 데 유용한 도구입니다. 이 랩에서는 이 형식 지정자를 사용하여 눈금 레이블에 선택된 문자열을 개선하고, 해당 눈금 레이블에 사용되는 문자열을 최대한 최소화하는 방법을 배우게 됩니다.

VM 팁

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

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

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

기본 형식 지정자

기본 형식 지정자와 그 상세한 출력을 먼저 살펴보겠습니다. 시간 경과에 따른 데이터를 플롯하고 기본 형식 지정자가 날짜와 시간을 어떻게 표시하는지 확인합니다.

import datetime
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates

## create time data
base = datetime.datetime(2005, 2, 1)
dates = [base + datetime.timedelta(hours=(2 * i)) for i in range(732)]
N = len(dates)
np.random.seed(19680801)
y = np.cumsum(np.random.randn(N))

## plot data
fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
lims = [(np.datetime64('2005-02'), np.datetime64('2005-04')),
        (np.datetime64('2005-02-03'), np.datetime64('2005-02-15')),
        (np.datetime64('2005-02-03 11:00'), np.datetime64('2005-02-04 13:20'))]
for nn, ax in enumerate(axs):
    ax.plot(dates, y)
    ax.set_xlim(lims[nn])
    ## rotate labels...
    for label in ax.get_xticklabels():
        label.set_rotation(40)
        label.set_horizontalalignment('right')
axs[0].set_title('Default Date Formatter')
plt.show()

간결한 날짜 형식 지정자

다음으로, ~.dates.ConciseDateFormatter와 그 출력을 살펴보겠습니다. 간결한 날짜 형식 지정자를 사용하여 새로운 플롯을 만들고, 이것이 기본 형식 지정자와 어떻게 다른지 확인합니다.

fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
for nn, ax in enumerate(axs):
    locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
    formatter = mdates.ConciseDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)

    ax.plot(dates, y)
    ax.set_xlim(lims[nn])
axs[0].set_title('Concise Date Formatter')
plt.show()

변환기 등록

날짜가 있는 모든 축 호출이 이 변환기를 사용하여 이루어지도록 하려면, 단위 레지스트리 (units registry) 를 사용하는 것이 가장 편리할 것입니다. 우리는 단위 레지스트리에 변환기를 등록하고 간결한 날짜 형식 지정자를 사용하여 데이터를 플롯합니다.

import datetime
import matplotlib.units as munits

converter = mdates.ConciseDateConverter()
munits.registry[np.datetime64] = converter
munits.registry[datetime.date] = converter
munits.registry[datetime.datetime] = converter

fig, axs = plt.subplots(3, 1, figsize=(6, 6), layout='constrained')
for nn, ax in enumerate(axs):
    ax.plot(dates, y)
    ax.set_xlim(lims[nn])
axs[0].set_title('Concise Date Formatter')
plt.show()

날짜 형식 현지화

기본 형식이 바람직하지 않은 경우, 세 개의 문자열 목록 중 하나를 조작하여 날짜 형식을 현지화할 수 있습니다. ISO "년 - 월 - 일" 대신 "일 - 월 - 년"으로 레이블을 수정합니다.

fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))

for nn, ax in enumerate(axs):
    locator = mdates.AutoDateLocator()
    formatter = mdates.ConciseDateFormatter(locator)
    formatter.formats = ['%y',  ## ticks are mostly years
                         '%b',       ## ticks are mostly months
                         '%d',       ## ticks are mostly days
                         '%H:%M',    ## hrs
                         '%H:%M',    ## min
                         '%S.%f', ]  ## secs
    ## these are mostly just the level above...
    formatter.zero_formats = [''] + formatter.formats[:-1]
    ## ...except for ticks that are mostly hours, then it is nice to have
    ## month-day:
    formatter.zero_formats[3] = '%d-%b'

    formatter.offset_formats = ['',
                                '%Y',
                                '%b %Y',
                                '%d %b %Y',
                                '%d %b %Y',
                                '%d %b %Y %H:%M', ]
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)

    ax.plot(dates, y)
    ax.set_xlim(lims[nn])
axs[0].set_title('Concise Date Formatter')
plt.show()

현지화와 함께 변환기 등록

~.dates.ConciseDateConverter에 키워드 인수를 전달하고, 사용할 데이터 유형을 단위 레지스트리 (units registry) 에 등록하여 현지화와 함께 변환기를 등록할 수도 있습니다.

import datetime

formats = ['%y',          ## ticks are mostly years
           '%b',     ## ticks are mostly months
           '%d',     ## ticks are mostly days
           '%H:%M',  ## hrs
           '%H:%M',  ## min
           '%S.%f', ]  ## secs
## these can be the same, except offset by one level....
zero_formats = [''] + formats[:-1]
## ...except for ticks that are mostly hours, then it's nice to have month-day
zero_formats[3] = '%d-%b'
offset_formats = ['',
                  '%Y',
                  '%b %Y',
                  '%d %b %Y',
                  '%d %b %Y',
                  '%d %b %Y %H:%M', ]

converter = mdates.ConciseDateConverter(
    formats=formats, zero_formats=zero_formats, offset_formats=offset_formats)

munits.registry[np.datetime64] = converter
munits.registry[datetime.date] = converter
munits.registry[datetime.datetime] = converter

fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
for nn, ax in enumerate(axs):
    ax.plot(dates, y)
    ax.set_xlim(lims[nn])
axs[0].set_title('Concise Date Formatter registered non-default')
plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 작업할 때 ~.dates.ConciseDateFormatter를 사용하여 날짜 눈금을 형식화하는 방법을 배웠습니다. 또한 날짜 형식을 현지화하고 변환기를 등록하여 프로세스를 더욱 편리하게 만드는 방법도 배웠습니다.