>  기사  >  백엔드 개발  >  Python은 3D 그래픽을 그립니다.

Python은 3D 그래픽을 그립니다.

不言
不言원래의
2018-05-03 11:44:3910301검색

이 글에서는 3D 그래픽을 그리는 데 주로 Python을 소개하는데, 이는 어느 정도 참고할만한 가치가 있습니다. 이제는 모든 사람과 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

3D 그래픽은 데이터 분석, 데이터 모델링, 그래픽 및 이미지 분야에서 사용됩니다. 여기에서는 3D 분산점, 3D 표면, 3D 윤곽선, 3D 직선(곡선) 그리기를 포함하여 Python을 사용하여 3D 그래픽을 그리는 방법을 소개합니다. 3D 텍스트.

준비 작업:

파이썬에서 3D 그래픽을 그리려면 흔히 사용되는 그리기 모듈인 matplotlib를 사용하지만, mpl_toolkits 툴킷을 설치해야 합니다. 설치 방법은 다음과 같습니다. Python 설치 디렉터리의 Scripts 폴더로 이동합니다. Windows 명령줄을 사용하여 다음을 실행합니다. pip Linux 환경에서 직접 --upgrade matplotlib를 설치하세요.

이 모듈을 설치한 후 mpl_tookits에서 mplot3d 클래스를 호출하여 3D 그래픽을 그릴 수 있습니다.

다음은 예시입니다.

1 나선형 3D 곡선의 결과는 다음과 같습니다.

3. 3D 윤곽선을 그립니다.

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
# Make data 
u = np.linspace(0, 2 * np.pi, 100) 
v = np.linspace(0, np.pi, 100) 
x = 10 * np.outer(np.cos(u), np.sin(v)) 
y = 10 * np.outer(np.sin(u), np.sin(v)) 
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) 
 
# Plot the surface 
ax.plot_surface(x, y, z, color='b') 
 
plt.show()

그리기 결과는 다음과 같습니다.

4. histogram

import matplotlib as mpl 
from mpl_toolkits.mplot3d import Axes3D 
import numpy as np 
import matplotlib.pyplot as plt 
 
mpl.rcParams['legend.fontsize'] = 10 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) 
z = np.linspace(-2, 2, 100) 
r = z**2 + 1 
x = r * np.sin(theta) 
y = r * np.cos(theta) 
ax.plot(x, y, z, label='parametric curve') 
ax.legend() 
 
plt.show()

그리기 결과는 다음과 같습니다.

5. 3D 메쉬 선을 그립니다.

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
from matplotlib import cm 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
X, Y, Z = axes3d.get_test_data(0.05) 
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) 
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) 
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) 
 
ax.set_xlabel('X') 
ax.set_xlim(-40, 40) 
ax.set_ylabel('Y') 
ax.set_ylim(-40, 40) 
ax.set_zlabel('Z') 
ax.set_zlim(-100, 100) 
 
plt.show()

그리기 결과는 다음과 같습니다.

6. 그리기 3D 삼각형 패치 다이어그램

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
x, y = np.random.rand(2, 100) * 4 
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]]) 
 
# Construct arrays for the anchor positions of the 16 bars. 
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos, 
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid 
# with indexing='ij'. 
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) 
xpos = xpos.flatten('F') 
ypos = ypos.flatten('F') 
zpos = np.zeros_like(xpos) 
 
# Construct arrays with the dimensions for the 16 bars. 
dx = 0.5 * np.ones_like(zpos) 
dy = dx.copy() 
dz = hist.flatten() 
 
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average') 
 
plt.show()

Draw 결과는 다음과 같습니다.

7. 3D 산점도 그리기

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
# Grab some test data. 
X, Y, Z = axes3d.get_test_data(0.05) 
 
# Plot a basic wireframe. 
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) 
 
plt.show()

결과는 다음과 같습니다.

8 . 3D 텍스트 그리기

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
 
n_radii = 8 
n_angles = 36 
 
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication). 
radii = np.linspace(0.125, 1.0, n_radii) 
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) 
 
# Repeat all angles for each radius. 
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) 
 
# Convert polar (radii, angles) coords to cartesian (x, y) coords. 
# (0, 0) is manually added at this stage, so there will be no duplicate 
# points in the (x, y) plane. 
x = np.append(0, (radii*np.cos(angles)).flatten()) 
y = np.append(0, (radii*np.sin(angles)).flatten()) 
 
# Compute z to make the pringle surface. 
z = np.sin(-x*y) 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
 
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True) 
 
plt.show(

그리기 결과는 다음과 같습니다.

9.3D 막대 차트

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
 
def randrange(n, vmin, vmax): 
 ''''' 
 Helper function to make an array of random numbers having shape (n, ) 
 with each number distributed Uniform(vmin, vmax). 
 ''' 
 return (vmax - vmin)*np.random.rand(n) + vmin 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
n = 100 
 
# For each set of style and range settings, plot n random points in the box 
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh]. 
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]: 
 xs = randrange(n, 23, 32) 
 ys = randrange(n, 0, 100) 
 zs = randrange(n, zlow, zhigh) 
 ax.scatter(xs, ys, zs, c=c, marker=m) 
 
ax.set_xlabel('X Label') 
ax.set_ylabel('Y Label') 
ax.set_zlabel('Z Label') 
 
plt.show()

그리기 결과는 다음과 같습니다.

관련 권장 사항:

파이썬을 사용하여 일반적으로 사용되는 차트 그리기


파이썬으로 그래픽 그리기 예제에 대한 자세한 설명

위 내용은 Python은 3D 그래픽을 그립니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.