Python 을 활용한 Matplotlib 시각화 제어

Beginner

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

소개

Matplotlib 은 Python 에서 정적, 애니메이션, 대화형 시각화를 생성하는 데 사용되는 데이터 시각화 라이브러리입니다. Tkinter, wxPython, Qt 또는 GTK 와 같은 범용 GUI 툴킷을 사용하여 응용 프로그램에 플롯을 임베딩하기 위한 객체 지향 API 를 제공합니다. 이 랩에서는 Python 을 사용하여 Matplotlib 에서 뷰 제한과 스티키 엣지를 제어하는 방법을 배우겠습니다.

VM 팁

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

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

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

여백으로 플로팅하기

Matplotlib 의 margins() 메서드는 set_xlim()set_ylim() 메서드를 사용하는 대신 플롯에 여백을 설정하는 데 사용할 수 있습니다. 이 단계에서는 set_xlim()set_ylim() 메서드 대신 margins() 메서드를 사용하여 플롯을 확대/축소하는 방법을 배우겠습니다.

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 3.0, 0.01)

## create a subplot with margins
ax1 = plt.subplot(212)
ax1.margins(0.05) ## default margin is 0.05, value 0 means fit
ax1.plot(t1, f(t1))

## create a subplot with zoomed out margins
ax2 = plt.subplot(221)
ax2.margins(2, 2) ## values >0.0 zoom out
ax2.plot(t1, f(t1))
ax2.set_title('Zoomed out')

## create a subplot with zoomed in margins
ax3 = plt.subplot(222)
ax3.margins(x=0, y=-0.25) ## values in (-0.5, 0.0) zooms in to center
ax3.plot(t1, f(t1))
ax3.set_title('Zoomed in')

plt.show()

스티키 엣지 (Sticky Edges)

Matplotlib 의 일부 플로팅 함수는 축 제한을 margins() 메서드에 "스티키 (sticky)"하거나 영향을 받지 않도록 합니다. 예를 들어, imshow()pcolor()는 사용자가 플롯에 표시된 픽셀 주변에 제한을 좁게 설정하기를 원한다고 예상합니다. 이 동작이 원치 않는 경우, use_sticky_edgesFalse로 설정해야 합니다. 이 단계에서는 Matplotlib 에서 스티키 엣지를 해결하는 방법을 배우겠습니다.

## create a grid
y, x = np.mgrid[:5, 1:6]

## define polygon coordinates
poly_coords = [
    (0.25, 2.75), (3.25, 2.75),
    (2.25, 0.75), (0.25, 0.75)
]

## create subplots
fig, (ax1, ax2) = plt.subplots(ncols=2)

## use sticky edges for ax1 and turn off sticky edges for ax2
ax2.use_sticky_edges = False

## plot on both subplots
for ax, status in zip((ax1, ax2), ('Is', 'Is Not')):
    cells = ax.pcolor(x, y, x+y, cmap='inferno', shading='auto') ## sticky
    ax.add_patch(
        Polygon(poly_coords, color='forestgreen', alpha=0.5)
    ) ## not sticky
    ax.margins(x=0.1, y=0.05)
    ax.set_aspect('equal')
    ax.set_title(f'{status} Sticky')

plt.show()

요약

이 랩에서는 Python 을 사용하여 Matplotlib 에서 뷰 제한 (view limits) 과 스티키 엣지 (sticky edges) 를 제어하는 방법을 배웠습니다. set_xlim()set_ylim() 메서드 대신 margins() 메서드를 사용하여 플롯을 확대/축소하는 방법을 배웠습니다. 또한 use_sticky_edges 속성을 사용하여 Matplotlib 에서 스티키 엣지를 해결하는 방법도 배웠습니다.