산점도 히스토그램 위치 지정 축

Beginner

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

소개

데이터 시각화에서 산점도 (scatter plot) 는 두 변수 간의 관계를 보여주는 데 사용됩니다. 또한, 히스토그램 (histogram) 은 단일 변수의 분포를 보여주는 데 유용합니다. 이 튜토리얼에서는 Python 의 Matplotlib 라이브러리를 사용하여 히스토그램과 함께 산점도를 만드는 방법을 배웁니다.

VM 팁

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

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

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

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

이 단계에서는 필요한 라이브러리를 가져오겠습니다.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable

랜덤 데이터 생성

이 단계에서는 산점도에 사용할 랜덤 데이터를 생성합니다.

np.random.seed(19680801)
x = np.random.randn(1000)
y = np.random.randn(1000)

산점도 생성

이 단계에서는 2 단계에서 생성한 랜덤 데이터를 사용하여 산점도를 생성합니다.

fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.scatter(x, y)
ax.set_aspect(1.)

히스토그램 생성

이 단계에서는 mpl_toolkits.axes_grid1에서 make_axes_locatable을 사용하여 x 및 y 변수에 대한 히스토그램을 생성합니다.

divider = make_axes_locatable(ax)
ax_histx = divider.append_axes("top", 1.2, pad=0.1, sharex=ax)
ax_histy = divider.append_axes("right", 1.2, pad=0.1, sharey=ax)

ax_histx.xaxis.set_tick_params(labelbottom=False)
ax_histy.yaxis.set_tick_params(labelleft=False)

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')

ax_histx.set_yticks([0, 50, 100])
ax_histy.set_xticks([0, 50, 100])

플롯 표시

이 단계에서는 히스토그램과 함께 산점도를 표시합니다.

plt.show()

요약

이 튜토리얼에서는 Python 의 Matplotlib 라이브러리를 사용하여 히스토그램과 함께 산점도를 생성하는 방법을 배웠습니다. 먼저 필요한 라이브러리를 가져온 다음, 산점도에 대한 임의의 데이터를 생성했습니다. 다음으로, make_axes_locatable을 사용하여 산점도와 히스토그램을 생성했습니다. 마지막으로, 플롯을 표시했습니다.