Matplotlib 를 이용한 3D 플롯에 2D 데이터 표시

Beginner

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

소개

이 랩에서는 ax.plotzdir 키워드를 사용하여 3D 플롯의 선택된 축에 2D 데이터를 플로팅하는 방법을 보여줍니다. Python 의 matplotlib 라이브러리를 사용하여 3D 플롯을 생성합니다.

VM 팁

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

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

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

라이브러리 임포트

첫 번째 단계는 필요한 라이브러리를 임포트하는 것입니다. 3D 그래프를 플로팅하기 위해 matplotlibnumpy가 필요합니다.

import matplotlib.pyplot as plt
import numpy as np

3D 플롯 생성

두 번째 단계는 ax = plt.figure().add_subplot(projection='3d')를 사용하여 3D 플롯을 생성하는 것입니다.

ax = plt.figure().add_subplot(projection='3d')

3D 플롯에 2D 데이터 플롯

세 번째 단계는 ax.plotax.scatter를 사용하여 3D 플롯에 2D 데이터를 플롯하는 것입니다. ax.plot 함수는 x 축과 y 축을 사용하여 사인 곡선을 플롯합니다. ax.scatter 함수는 x 축과 z 축에 산점도 데이터를 플롯합니다.

## Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')

## Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')

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

x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
    c_list.extend([c] * 20)
## By using zdir='y', the y value of these points is fixed to the zs value 0
## and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')

플롯 사용자 정의

네 번째 단계는 범례를 추가하고, 축 제한 및 레이블을 설정하고, 뷰 각도를 변경하여 플롯을 사용자 정의하는 것입니다.

## Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

## Customize the view angle so it's easier to see that the scatter points lie
## on the plane y=0
ax.view_init(elev=20., azim=-35, roll=0)

plt.show()

플롯 보기

마지막 단계는 코드를 실행하여 3D 플롯을 보는 것입니다.

요약

이 랩에서는 ax.plotzdir 키워드를 사용하여 3D 플롯의 선택된 축에 2D 데이터를 플로팅하는 방법을 배웠습니다. 또한 범례를 추가하고, 축 제한 및 레이블을 설정하고, 뷰 각도를 변경하여 플롯을 사용자 정의하는 방법도 배웠습니다.