소개
이 랩에서는 Matplotlib 을 사용하여 히스토그램이 있는 산점도를 만드는 방법을 안내합니다. 히스토그램이 있는 산점도는 두 변수의 분포와 그 관계를 시각화하는 훌륭한 방법입니다. 산점도는 두 변수 간의 관계를 표시하고, 히스토그램은 각 변수의 분포를 독립적으로 보여줍니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하세요.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
라이브러리 임포트
시작하기 전에 필요한 라이브러리를 임포트해야 합니다. 이 랩에서는 Matplotlib 과 NumPy 를 사용합니다.
import matplotlib.pyplot as plt
import numpy as np
랜덤 데이터 생성
산점도와 히스토그램에 사용할 임의의 데이터를 생성합니다.
## Fixing random state for reproducibility
np.random.seed(19680801)
## Generate random data
x = np.random.randn(1000)
y = np.random.randn(1000)
scatter_hist 함수 정의
x 와 y 데이터, 그리고 산점도용 메인 축과 두 개의 주변 축, 총 세 개의 축을 입력으로 받는 scatter_hist 함수를 정의해야 합니다. 이 함수는 제공된 축 내에서 산점도와 히스토그램을 생성합니다.
def scatter_hist(x, y, ax, ax_histx, ax_histy):
## Remove labels from the histograms
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
## Create the scatter plot
ax.scatter(x, y)
## Determine nice limits by hand
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1) * binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins)
ax_histy.hist(y, bins=bins, orientation='horizontal')
gridspec 을 사용하여 축 위치 정의
이제 원하는 레이아웃을 얻기 위해 불균등한 너비 및 높이 비율을 가진 gridspec을 정의합니다. 또한 축을 생성하고 이를 scatter_hist 함수에 전달합니다.
## Start with a square Figure.
fig = plt.figure(figsize=(6, 6))
## Add a gridspec with two rows and two columns and a ratio of 1 to 4 between
## the size of the marginal axes and the main axes in both directions.
## Also adjust the subplot parameters for a square plot.
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4),
left=0.1, right=0.9, bottom=0.1, top=0.9,
wspace=0.05, hspace=0.05)
## Create the Axes.
ax = fig.add_subplot(gs[1, 0])
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
inset_axes 를 사용하여 축 위치 정의
inset_axes를 사용하여 주변 축을 메인 축 외부에 배치할 수도 있습니다. 이렇게 하면 메인 축의 종횡비를 고정할 수 있고, 주변 축은 항상 축의 위치를 기준으로 그려진다는 장점이 있습니다.
## Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
## Create the main axes, leaving 25% of the figure space at the top and on the right to position marginals.
ax = fig.add_gridspec(top=0.75, right=0.75).subplots()
## The main axes' aspect can be fixed.
ax.set(aspect=1)
## Create marginal axes, which have 25% of the size of the main axes.
## Note that the inset axes are positioned *outside* (on the right and the top) of the main axes,
## by specifying axes coordinates greater than 1.
## Axes coordinates less than 0 would likewise specify positions on the left and the bottom of the main axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
플롯 표시
마지막으로, plt.show()를 사용하여 플롯을 표시할 수 있습니다.
plt.show()
요약
이 랩에서는 Matplotlib 을 사용하여 히스토그램이 있는 산점도를 만드는 방법을 배웠습니다. scatter_hist 함수를 정의하고, 임의 데이터를 생성하고, gridspec 및 inset_axes를 사용하여 축 위치를 정의하고, 플롯을 표시했습니다. 히스토그램이 있는 산점도는 두 변수의 분포와 그 관계를 시각화하는 훌륭한 방법입니다.