Matplotlib 을 이용한 확대된 삽입 생성

Beginner

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

소개

Matplotlib 는 Python 에서 널리 사용되는 데이터 시각화 라이브러리입니다. 다양한 유형의 플롯과 그래프를 생성하는 많은 도구를 제공합니다. Matplotlib 의 유용한 기능 중 하나는 플롯의 특정 영역을 확대하여 데이터를 더 자세히 분석하는 기능입니다. 이 랩에서는 Matplotlib 를 사용하여 확대된 삽입 (inset) 을 만드는 방법을 배우겠습니다.

VM 팁

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

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

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

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

확대된 삽입을 만들기 전에 필요한 라이브러리를 가져와야 합니다. 이 랩에서는 matplotlib.pyplotnumpy를 사용합니다.

import matplotlib.pyplot as plt
import numpy as np

figure 와 subplot 생성

다음으로, 데이터를 표시하기 위해 figure 와 subplot 을 생성합니다. 확대된 삽입의 두 가지 다른 예시를 나란히 표시하기 위해 두 개의 subplot 을 생성합니다.

fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])

크기 막대가 있는 확대된 삽입 생성

첫 번째 subplot 에서 크기 막대가 있는 확대된 삽입을 생성합니다. 이는 .zoomed_inset_axes 메서드를 사용하여 확대된 삽입을 만드는 방법을 보여줍니다.

## Set the aspect ratio of the plot to 1
ax.set_aspect(1)

## Create a zoomed inset in the upper right corner of the plot
axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')

## Set the number of ticks on the inset axes
axins.yaxis.get_major_locator().set_params(nbins=7)
axins.xaxis.get_major_locator().set_params(nbins=7)

## Hide the tick labels on the inset axes
axins.tick_params(labelleft=False, labelbottom=False)

## Define a function to add a size bar to the plot
def add_sizebar(ax, size):
    asb = AnchoredSizeBar(ax.transData,
                          size,
                          str(size),
                          loc=8,
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)

## Add a size bar to the main plot and the inset plot
add_sizebar(ax, 0.5)
add_sizebar(axins, 0.5)

삽입 확대 및 표시된 삽입이 있는 이미지 생성

두 번째 subplot 에서 삽입 확대 및 표시된 삽입이 있는 이미지를 생성합니다. 이는 .mark_inset 메서드를 사용하여 관심 영역을 표시하고 이를 삽입 축에 연결하는 방법을 보여줍니다.

## Load sample data for the image
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")  ## 15x15 array
extent = (-3, 4, -4, 3)
Z2 = np.zeros((150, 150))
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z

## Display the image in the subplot
ax2.imshow(Z2, extent=extent, origin="lower")

## Create a zoomed inset in the upper left corner of the plot
axins2 = zoomed_inset_axes(ax2, zoom=6, loc=1)

## Display the image in the inset plot
axins2.imshow(Z2, extent=extent, origin="lower")

## Set the x and y limits of the inset plot to show the region of interest
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins2.set_xlim(x1, x2)
axins2.set_ylim(y1, y2)

## Set the number of ticks on the inset axes
axins2.yaxis.get_major_locator().set_params(nbins=7)
axins2.xaxis.get_major_locator().set_params(nbins=7)

## Hide the tick labels on the inset axes
axins2.tick_params(labelleft=False, labelbottom=False)

## Mark the region of interest and connect it to the inset axes
mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")

플롯 표시

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

plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 확대된 삽입을 만드는 방법을 배웠습니다. .zoomed_inset_axes.mark_inset 메서드를 사용하여 두 가지 다른 예시의 확대된 삽입을 만들었습니다. 이러한 메서드를 사용함으로써 데이터를 더 자세히 분석하고 원래 플롯에서는 보이지 않을 수 있는 통찰력을 얻을 수 있습니다.