Matplotlib 비 시뮬레이션

Beginner

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

소개

이 랩은 Python 의 Matplotlib 라이브러리를 사용하여 비 시뮬레이션을 만드는 방법에 대한 단계별 튜토리얼입니다. 시뮬레이션은 표면에 떨어지는 빗방울을 시뮬레이션하기 위해 50 개의 산점 (scatter point) 의 크기와 불투명도를 애니메이션화합니다.

VM 팁

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

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

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

새로운 Figure 와 Axes 생성

첫 번째 단계는 새로운 figure 와 이를 채우는 axes 를 생성하는 것입니다. 이것이 시뮬레이션이 그려질 캔버스가 됩니다.

fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])

비 데이터 생성

다음으로, 비 데이터를 생성합니다. 무작위 위치, 무작위 성장률 및 무작위 색상으로 50 개의 빗방울을 생성합니다.

n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, (2,)),
                                      ('size',     float),
                                      ('growth',   float),
                                      ('color',    float, (4,))])

rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)

산점도 구성

이제 애니메이션 동안 빗방울이 발달함에 따라 업데이트될 산점도 (scatter plot) 를 구성합니다.

scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
                  s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
                  facecolors='none')

업데이트 함수 생성

업데이트 함수는 애니메이션 동안 산점도를 업데이트하기 위해 FuncAnimation 객체에 의해 호출됩니다.

def update(frame_number):
    ## Get an index which we can use to re-spawn the oldest raindrop.
    current_index = frame_number % n_drops

    ## Make all colors more transparent as time progresses.
    rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
    rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)

    ## Make all circles bigger.
    rain_drops['size'] += rain_drops['growth']

    ## Pick a new position for oldest rain drop, resetting its size,
    ## color and growth factor.
    rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
    rain_drops['size'][current_index] = 5
    rain_drops['color'][current_index] = (0, 0, 0, 1)
    rain_drops['growth'][current_index] = np.random.uniform(50, 200)

    ## Update the scatter collection, with the new colors, sizes and positions.
    scat.set_edgecolors(rain_drops['color'])
    scat.set_sizes(rain_drops['size'])
    scat.set_offsets(rain_drops['position'])

애니메이션 생성

마지막으로, FuncAnimation 객체를 사용하여 애니메이션을 생성합니다. 이 때 figure, update 함수, 프레임 간 간격 (밀리초) 및 저장할 프레임 수를 전달합니다.

animation = FuncAnimation(fig, update, interval=10, save_count=100)
plt.show()

요약

이 랩에서는 Python 의 Matplotlib 라이브러리를 사용하여 비 시뮬레이션을 만드는 방법을 배웠습니다. 새로운 Figure 와 Axes 를 생성하고, 비 데이터를 생성하고, 산점도를 구성하고, update 함수를 생성하고, FuncAnimation 객체를 사용하여 애니메이션을 생성했습니다.