Matplotlib 시각화 기본

Beginner

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

소개

이 랩에서는 시각화를 생성하기 위한 Python 라이브러리인 Matplotlib 을 사용하여 그림을 만들고 해부학적 구조에 주석을 다는 방법을 배우게 됩니다. 그림을 만들고, 데이터를 플롯하고, 축 제한을 설정하고, 레이블과 제목을 추가하고, 텍스트와 마커로 그림에 주석을 다는 방법을 배우게 됩니다.

VM 팁

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

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

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

라이브러리 가져오기 및 데이터 설정

먼저, 필요한 라이브러리를 가져오고 플롯할 데이터를 설정해야 합니다. 이 예제에서는 세 개의 사인파를 플롯하고, 여기에 약간의 무작위 노이즈를 추가할 것입니다.

import matplotlib.pyplot as plt
import numpy as np

## Set up data
np.random.seed(19680801)

X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))

그림 생성 및 축 설정

다음으로, 그림을 생성하고 축을 설정합니다. add_axes() 메서드를 사용하여 그림 내에 새로운 축 집합을 생성합니다. 또한 x 및 y 축의 제한을 설정하고 그리드 선을 추가합니다.

## Create figure and axes
fig = plt.figure(figsize=(7.5, 7.5))
ax = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1)

## Set limits and gridlines
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)

데이터 플롯

이제 방금 생성한 축에 데이터를 플롯합니다. plot() 메서드를 사용하여 세 개의 사인파를 서로 다른 색상과 선 너비로 플롯합니다.

## Plot data
ax.plot(X, Y1, c='C0', lw=2.5, label="Blue signal", zorder=10)
ax.plot(X, Y2, c='C1', lw=2.5, label="Orange signal")
ax.plot(X[::3], Y3[::3], linewidth=0, markersize=9,
        marker='s', markerfacecolor='none', markeredgecolor='C4',
        markeredgewidth=2.5)

레이블 및 제목 추가

이제 set_xlabel(), set_ylabel(), 및 set_title() 메서드를 사용하여 x 및 y 축에 레이블을 추가하고 그림에 제목을 추가합니다.

## Add labels and title
ax.set_xlabel("x Axis label", fontsize=14)
ax.set_ylabel("y Axis label", fontsize=14)
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')

범례 추가

legend() 메서드를 사용하여 그림에 범례를 추가합니다. 또한 범례의 위치와 글꼴 크기를 지정합니다.

## Add legend
ax.legend(loc="upper right", fontsize=14)

그림 주석

마지막으로, text()Circle() 메서드를 사용하여 다양한 Matplotlib 요소의 이름을 표시하기 위해 그림에 주석을 추가합니다. 또한 가시성을 높이기 위해 withStroke() 메서드를 사용하여 텍스트와 마커에 흰색 윤곽선을 추가합니다.

## Annotate the figure
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke

royal_blue = [0, 20/256, 82/256]

def annotate(x, y, text, code):
    ## Circle marker
    c = Circle((x, y), radius=0.15, clip_on=False, zorder=10, linewidth=2.5,
               edgecolor=royal_blue + [0.6], facecolor='none',
               path_effects=[withStroke(linewidth=7, foreground='white')])
    ax.add_artist(c)

    ## use path_effects as a background for the texts
    ## draw the path_effects and the colored text separately so that the
    ## path_effects cannot clip other texts
    for path_effects in [[withStroke(linewidth=7, foreground='white')], []]:
        color = 'white' if path_effects else royal_blue
        ax.text(x, y-0.2, text, zorder=100,
                ha='center', va='top', weight='bold', color=color,
                style='italic', fontfamily='Courier New',
                path_effects=path_effects)

        color = 'white' if path_effects else 'black'
        ax.text(x, y-0.33, code, zorder=100,
                ha='center', va='top', weight='normal', color=color,
                fontfamily='monospace', fontsize='medium',
                path_effects=path_effects)

annotate(3.5, -0.13, "Minor tick label", "ax.xaxis.set_minor_formatter")
annotate(-0.03, 1.0, "Major tick", "ax.yaxis.set_major_locator")
annotate(0.00, 3.75, "Minor tick", "ax.yaxis.set_minor_locator")
annotate(-0.15, 3.00, "Major tick label", "ax.yaxis.set_major_formatter")
annotate(1.68, -0.39, "xlabel", "ax.set_xlabel")
annotate(-0.38, 1.67, "ylabel", "ax.set_ylabel")
annotate(1.52, 4.15, "Title", "ax.set_title")
annotate(1.75, 2.80, "Line", "ax.plot")
annotate(2.25, 1.54, "Markers", "ax.scatter")
annotate(3.00, 3.00, "Grid", "ax.grid")
annotate(3.60, 3.58, "Legend", "ax.legend")
annotate(2.5, 0.55, "Axes", "fig.subplots")
annotate(4, 4.5, "Figure", "plt.figure")
annotate(0.65, 0.01, "x Axis", "ax.xaxis")
annotate(0, 0.36, "y Axis", "ax.yaxis")
annotate(4.0, 0.7, "Spine", "ax.spines")

요약

이 랩에서는 Matplotlib 을 사용하여 그림을 만들고 해부학적 구조에 주석을 추가하는 방법을 배웠습니다. 그림을 만들고, 데이터를 플롯하고, 축 제한을 설정하고, 레이블과 제목을 추가하고, 텍스트와 마커로 그림에 주석을 추가하는 방법을 배웠습니다. 이 랩의 단계를 따르면 이제 Python 에서 Matplotlib 을 사용하여 그림을 만들고 주석을 추가하는 방법에 대한 훌륭한 이해를 갖게 될 것입니다.