Matplotlib 틱 포맷터 튜토리얼

Beginner

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

소개

Matplotlib 는 고품질 2D 및 3D 그래프를 생성하는 널리 사용되는 Python 플로팅 라이브러리입니다. 이 랩에서는 Matplotlib 에서 틱 포맷터 (tick formatter) 를 사용하는 방법을 배우겠습니다.

VM 팁

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

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

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

Matplotlib 가져오기 및 플롯 설정

먼저 Matplotlib 라이브러리를 가져와 플롯을 설정해야 합니다. 하나의 y 축과 하나의 x 축이 있는 빈 플롯을 생성합니다. 또한 하단 스파인 (spine) 만 표시하도록 축을 구성하고, 틱 위치를 설정하고, 틱 길이를 정의합니다.

import matplotlib.pyplot as plt
from matplotlib import ticker

def setup(ax, title):
    """Set up common parameters for the Axes in the example."""
    ## only show the bottom spine
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines[['left', 'right', 'top']].set_visible(False)

    ## define tick positions
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))

    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.text(0.0, 0.2, title, transform=ax.transAxes,
            fontsize=14, fontname='Monospace', color='tab:blue')


fig, ax = plt.subplots(figsize=(8, 2))
setup(ax, "Tick Formatters")

간단한 서식 지정

이 단계에서는 문자열 또는 함수를 ~.Axis.set_major_formatter 또는 ~.Axis.set_minor_formatter에 전달하여 간단한 포맷터 (formatter) 를 사용하는 방법을 보여줍니다. 문자열 포맷터와 함수 포맷터를 사용하는 두 개의 플롯을 생성합니다.

fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
fig0.suptitle('Simple Formatting')

## A ``str``, using format string function syntax, can be used directly as a
## formatter.  The variable ``x`` is the tick value and the variable ``pos`` is
## tick position.  This creates a StrMethodFormatter automatically.
setup(axs0[0], title="'{x} km'")
axs0[0].xaxis.set_major_formatter('{x} km')

## A function can also be used directly as a formatter. The function must take
## two arguments: ``x`` for the tick value and ``pos`` for the tick position,
## and must return a ``str``. This creates a FuncFormatter automatically.
setup(axs0[1], title="lambda x, pos: str(x-5)")
axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))

fig0.tight_layout()

포맷터 (Formatter) 객체 서식 지정

이 단계에서는 .Formatter 객체를 사용하여 틱 (tick) 을 서식 지정합니다. 서로 다른 포맷터를 사용하는 7 개의 플롯을 생성합니다.

fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
fig1.suptitle('Formatter Object Formatting')

## Null formatter
setup(axs1[0], title="NullFormatter()")
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())

## StrMethod formatter
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))

## FuncFormatter can be used as a decorator
@ticker.FuncFormatter
def major_formatter(x, pos):
    return f'[{x:.2f}]'

setup(axs1[2], title='FuncFormatter("[{:.2f}]".format)')
axs1[2].xaxis.set_major_formatter(major_formatter)

## Fixed formatter
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C', ...])")
## FixedFormatter should only be used together with FixedLocator.
## Otherwise, one cannot be sure where the labels will end up.
positions = [0, 1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))
axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))

## Scalar formatter
setup(axs1[4], title="ScalarFormatter()")
axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

## FormatStr formatter
setup(axs1[5], title="FormatStrFormatter('#%d')")
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))

## Percent formatter
setup(axs1[6], title="PercentFormatter(xmax=5)")
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))

fig1.tight_layout()

플롯 표시

마지막으로, plt.show()를 사용하여 플롯을 표시합니다.

plt.show()

요약

이 랩에서는 문자열 또는 함수를 ~.Axis.set_major_formatter 또는 ~.Axis.set_minor_formatter에 전달하거나, 다양한 ~.ticker.Formatter 클래스 중 하나의 인스턴스를 생성하여 ~.Axis.set_major_formatter 또는 ~.Axis.set_minor_formatter에 제공함으로써 Matplotlib 에서 틱 (tick) 포맷터를 사용하는 방법을 배웠습니다. 또한 틱 위치, 틱 길이 및 제목으로 플롯을 설정하는 방법도 배웠습니다.