소개
이 랩은 Matplotlib 을 사용하여 데이터 시각화의 기본 사항을 소개하도록 설계되었습니다. Matplotlib 은 Python 을 위한 널리 사용되는 데이터 시각화 라이브러리로, 플롯, 그래프 및 차트를 생성하기 위한 광범위한 옵션을 제공합니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
설정
시작하기 전에 Matplotlib 이 설치되었는지 확인해야 합니다. 다음 명령을 실행하여 pip 를 사용하여 설치할 수 있습니다.
!pip install matplotlib
설치가 완료되면 라이브러리를 가져오고 환경을 설정해야 합니다.
import matplotlib.pyplot as plt
import numpy as np
## Fixing random state for reproducibility
np.random.seed(19680801)
## Create new Figure with black background
fig = plt.figure(figsize=(8, 8), facecolor='black')
## Add a subplot with no frame
ax = plt.subplot(frameon=False)
랜덤 데이터 생성
이 단계에서는 플롯을 생성하는 데 사용할 랜덤 데이터를 생성합니다.
## Generate random data
data = np.random.uniform(0, 1, (64, 75))
X = np.linspace(-1, 1, data.shape[-1])
G = 1.5 * np.exp(-4 * X ** 2)
선 그래프 생성
이전 단계에서 생성한 랜덤 데이터를 사용하여 선 그래프를 생성합니다.
## Generate line plots
lines = []
for i in range(len(data)):
## Small reduction of the X extents to get a cheap perspective effect
xscale = 1 - i / 200.
## Same for linewidth (thicker strokes on bottom)
lw = 1.5 - i / 100.0
line, = ax.plot(xscale * X, i + G * data[i], color="w", lw=lw)
lines.append(line)
한계 설정 및 눈금 제거
이 단계에서는 y 축 한계를 설정하고 플롯에서 눈금을 제거합니다.
## Set y limit (or first line is cropped because of thickness)
ax.set_ylim(-1, 70)
## No ticks
ax.set_xticks([])
ax.set_yticks([])
제목 추가
플롯에 제목을 추가합니다.
## 2 part titles to get different font weights
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
ha="right", va="bottom", color="w",
family="sans-serif", fontweight="light", fontsize=16)
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
ha="left", va="bottom", color="w",
family="sans-serif", fontweight="bold", fontsize=16)
플롯 애니메이션
이제 데이터를 오른쪽으로 이동하고 새로운 값을 채워 플롯을 애니메이션화합니다.
import matplotlib.animation as animation
def update(*args):
## Shift all data to the right
data[:, 1:] = data[:, :-1]
## Fill-in new values
data[:, 0] = np.random.uniform(0, 1, len(data))
## Update data
for i in range(len(data)):
lines[i].set_ydata(i + G * data[i])
## Return modified artists
return lines
## Construct the animation, using the update function as the animation director.
anim = animation.FuncAnimation(fig, update, interval=10, save_count=100)
plt.show()
요약
이 랩에서는 Matplotlib 을 사용하여 데이터 시각화의 기본 사항을 배웠습니다. 무작위 데이터를 생성하고, 선 그래프를 만들고, 제한을 설정하고 눈금을 제거하고, 제목을 추가하고, 플롯을 애니메이션화했습니다. 이것들은 단지 기본 사항일 뿐이며, Matplotlib 은 시각화를 사용자 정의하고 향상시키기 위한 더 많은 옵션을 제공합니다.