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
import matplotlib.animation as animation

랜덤 시드 및 Bin 설정

재현성을 위해 랜덤 시드를 설정하고 bin 경계를 고정합니다.

## Fixing random state for reproducibility
np.random.seed(19680801)

## Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)

데이터 및 히스토그램 생성

NumPy 를 사용하여 데이터와 히스토그램을 생성합니다.

## histogram our data with numpy
data = np.random.randn(1000)
n, _, _ = plt.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)

애니메이션 함수 생성

새로운 랜덤 데이터를 생성하고 사각형의 높이를 업데이트하는 animate 함수를 생성해야 합니다.

def animate(frame_number):
    ## simulate new data coming in
    data = np.random.randn(1000)
    n, _ = np.histogram(data, HIST_BINS)
    for count, rect in zip(n, bar_container.patches):
        rect.set_height(count)
    return bar_container.patches

막대 컨테이너 및 애니메이션 생성

plt.hist를 사용하면 Rectangle 인스턴스의 모음인 BarContainer의 인스턴스를 얻을 수 있습니다. FuncAnimation을 사용하여 애니메이션을 설정합니다.

## Using plt.hist allows us to get an instance of BarContainer, which is a
## collection of Rectangle instances. Calling prepare_animation will define
## animate function working with supplied BarContainer, all this is used to setup FuncAnimation.
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)
ax.set_ylim(top=55)  ## set safe limit to ensure that all data is visible.

ani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True)
plt.show()

요약

이 랩에서는 Python 에서 Matplotlib 을 사용하여 애니메이션 히스토그램을 만드는 방법을 배웠습니다. 필요한 라이브러리를 가져오고, 랜덤 시드 (random seed) 와 빈 (bin) 을 설정하고, 데이터를 생성하고 히스토그램을 만들고, 애니메이션 함수를 생성한 다음, 막대 컨테이너와 애니메이션을 생성하는 것으로 시작했습니다. 이러한 단계를 따르면 데이터를 동적으로 시각화하기 위해 애니메이션 히스토그램을 만들 수 있습니다.