Matplotlib 스파인 위치 조정

Beginner

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

소개

Matplotlib 에서 축 스파인 (axis spines) 의 위치를 조정하여 플롯의 모양을 사용자 정의할 수 있습니다. 이 랩에서는 Matplotlib 에서 스파인 위치를 조정하는 과정을 안내합니다.

VM 팁

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

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

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

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

이 단계에서는 플롯을 생성하는 데 필요한 라이브러리를 가져오겠습니다.

import matplotlib.pyplot as plt
import numpy as np

기본 플롯 생성

이 단계에서는 Matplotlib 에서 다양한 스파인 (spine) 배치 옵션을 보여주기 위해 기본 플롯을 생성합니다.

x = np.linspace(0, 2*np.pi, 100)
y = 2 * np.sin(x)

fig, ax_dict = plt.subplot_mosaic(
    [['center', 'zero'],
     ['axes', 'data']]
)
fig.suptitle('Spine positions')

ax = ax_dict['center']
ax.set_title("'center'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('center')
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['zero']
ax.set_title("'zero'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('zero')
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['axes']
ax.set_title("'axes' (0.2, 0.2)")
ax.plot(x, y)
ax.spines.left.set_position(('axes', 0.2))
ax.spines.bottom.set_position(('axes', 0.2))
ax.spines[['top', 'right']].set_visible(False)

ax = ax_dict['data']
ax.set_title("'data' (1, 2)")
ax.plot(x, y)
ax.spines.left.set_position(('data', 1))
ax.spines.bottom.set_position(('data', 2))
ax.spines[['top', 'right']].set_visible(False)

스파인 위치 조정 메서드 정의

이 단계에서는 지정된 스파인 위치를 기반으로 축 스파인의 위치를 조정하는 메서드를 정의합니다.

def adjust_spines(ax, spines):
    """
    지정된 스파인 위치를 기반으로 축 스파인의 위치를 조정합니다.

    Parameters:
        ax (Axes): 스파인을 조정할 Matplotlib Axes 객체입니다.
        spines (list of str): 원하는 스파인 위치입니다. 유효한 옵션은 'left', 'right', 'top', 'bottom'입니다.

    Returns:
        None
    """
    for loc, spine in ax.spines.items():
        if loc in spines:
            spine.set_position(('outward', 10))  ## move the spine outward by 10 points
        else:
            spine.set_color('none')  ## don't draw the spine

    ## turn off ticks where there is no spine
    if 'left' in spines:
        ax.yaxis.set_ticks_position('left')
    else:
        ax.yaxis.set_ticks([])

    if 'bottom' in spines:
        ax.xaxis.set_ticks_position('bottom')
    else:
        ax.xaxis.set_ticks([])

adjust_spines 메서드를 사용하여 플롯 생성

이 단계에서는 adjust_spines 메서드를 사용하여 스파인 위치를 조정하는 방법을 보여주는 플롯을 생성합니다.

fig = plt.figure()

x = np.linspace(0, 2 * np.pi, 100)
y = 2 * np.sin(x)

ax = fig.add_subplot(2, 2, 1)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left'])

ax = fig.add_subplot(2, 2, 2)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, [])

ax = fig.add_subplot(2, 2, 3)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left', 'bottom'])

ax = fig.add_subplot(2, 2, 4)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['bottom'])

plt.show()

요약

이 랩에서는 set_position 메서드를 사용하여 축 스파인의 위치를 설정하여 Matplotlib 에서 스파인 위치를 조정하는 방법과 원하는 스파인 위치를 기반으로 스파인 위치를 조정하는 메서드를 정의하는 방법을 배웠습니다. 이는 플롯의 모양을 사용자 정의하고 특정 기능을 강조 표시하는 데 유용할 수 있습니다.