Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Tutorial terperinci tentang melukis graf tiga dimensi dalam python

Tutorial terperinci tentang melukis graf tiga dimensi dalam python

WBOY
WBOYke hadapan
2022-08-30 12:04:2010680semak imbas

[Cadangan berkaitan: Tutorial video Python3]

Artikel ini hanya meringkaskan kaedah lukisan yang paling asas.

1. Permulaan

Diandaikan bahawa pakej alat matplotlib telah dipasang.

Gunakan matplotlib.figure.Rajah untuk mencipta bingkai plot:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

2. Plot garisan (Plot garis)

Penggunaan Asas:

ax.plot(x,y,z,label=' ')

kod:

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()

3 Petak serakan (Petak serakan)

Penggunaan asas: <.>

ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True, *args, *kwargs)
    xs, ys, zs: data input;
  • s: saiz titik taburan
  • c: warna, contohnya, c = 'r' adalah merah ;
  • depthshase: ketelusan, Benar adalah lutsinar, lalai ialah Benar, Salah adalah legap
  • *args dan pembolehubah sambungan lain, seperti maker = 'o', kemudian hasil serakan ialah 'o' Shape
kod:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
 
 
def randrange(n, vmin, vmax):
    &#39;&#39;&#39;
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    &#39;&#39;&#39;
    return (vmax - vmin)*np.random.rand(n) + vmin
 
fig = plt.figure()
ax = fig.add_subplot(111, projection=&#39;3d&#39;)
 
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 [(&#39;r&#39;, &#39;o&#39;, -50, -25), (&#39;b&#39;, &#39;^&#39;, -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(&#39;X Label&#39;)
ax.set_ylabel(&#39;Y Label&#39;)
ax.set_zlabel(&#39;Z Label&#39;)
 
plt.show()

4. Petak rangka wayar

Penggunaan asas:

ax.plot_wireframe(X, Y, Z, *args, **kwargs)
    X, Y, Z: data input
  • rstride: panjang langkah baris
  • cstride: panjang langkah lajur
  • rcount: bilangan baris Had atas
  • akaun: Had atas bilangan lajur
kod:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
 
 
fig = plt.figure()
ax = fig.add_subplot(111, projection=&#39;3d&#39;)
 
# 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()

5. Petak permukaan

Penggunaan asas:

ax.plot_surface(X, Y, Z, *args, **kwargs)
    X, Y, Z: data
  • rstride, cstride, rcount, ccount: sama seperti definisi plot Wireframe
  • warna: warna permukaan
  • cmap: lapisan
kod:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
 
 
fig = plt.figure()
ax = fig.gca(projection=&#39;3d&#39;)
 
# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
 
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
 
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter(&#39;%.02f&#39;))
 
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
 
plt.show()

6. Peta permukaan segi tiga ( Plot Tri-Surface)

Penggunaan asas:

ax.plot_trisurf(*args, **kwargs)
    X, Y, Z: data
  • Parameter lain serupa dengan plot permukaan
kod:

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=&#39;3d&#39;)
 
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
 
plt.show()

7 Plot kontur

Penggunaan asas:

ax.contour(X, Y, Z, *args, **kwargs)
kod:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
 
fig = plt.figure()
ax = fig.add_subplot(111, projection=&#39;3d&#39;)
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
 
plt.show()

Kontur dua dimensi juga boleh dilukis bersama dengan peta permukaan tiga dimensi:

kod:

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

Ia juga boleh menjadi unjuran kontur tiga dimensi pada satah dua dimensi:

kod:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
 
fig = plt.figure()
ax = fig.gca(projection=&#39;3d&#39;)
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir=&#39;z&#39;, offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir=&#39;x&#39;, offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir=&#39;y&#39;, offset=40, cmap=cm.coolwarm)
 
ax.set_xlabel(&#39;X&#39;)
ax.set_xlim(-40, 40)
ax.set_ylabel(&#39;Y&#39;)
ax.set_ylim(-40, 40)
ax.set_zlabel(&#39;Z&#39;)
ax.set_zlim(-100, 100)
 
plt.show()

8. Plot bar (carta bar)

Penggunaan asas:

ax.bar(left, height, zs=0, zdir=&#39;z&#39;, *args, **kwargs
    x, y, zs = z, data
  • zdir : Arah planarisasi carta bar boleh difahami secara terperinci mengikut kod.
kod:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
 
fig = plt.figure()
ax = fig.add_subplot(111, projection=&#39;3d&#39;)
for c, z in zip([&#39;r&#39;, &#39;g&#39;, &#39;b&#39;, &#39;y&#39;], [30, 20, 10, 0]):
    xs = np.arange(20)
    ys = np.random.rand(20)
 
    # You can provide either a single color or an array. To demonstrate this,
    # the first bar of each set will be colored cyan.
    cs = [c] * len(xs)
    cs[0] = &#39;c&#39;
    ax.bar(xs, ys, zs=z, zdir=&#39;y&#39;, color=cs, alpha=0.8)
 
ax.set_xlabel(&#39;X&#39;)
ax.set_ylabel(&#39;Y&#39;)
ax.set_zlabel(&#39;Z&#39;)
 
plt.show()

9 Subplot (subplot)

A-Grafik 2-D yang berbeza diedarkan. dalam ruang 3-D sebenarnya, ruang unjuran tidak kosong, kod yang sepadan:

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
 
fig = plt.figure()
ax = fig.gca(projection=&#39;3d&#39;)
 
# 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=&#39;z&#39;, label=&#39;curve in (x,y)&#39;)
 
# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = (&#39;r&#39;, &#39;g&#39;, &#39;b&#39;, &#39;k&#39;)
x = np.random.sample(20*len(colors))
y = np.random.sample(20*len(colors))
c_list = []
for c in colors:
    c_list.append([c]*20)
# By using zdir=&#39;y&#39;, 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=&#39;y&#39;, c=c_list, label=&#39;points in (x,z)&#39;)
 
# 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(&#39;X&#39;)
ax.set_ylabel(&#39;Y&#39;)
ax.set_zlabel(&#39;Z&#39;)

Penggunaan Subplot B-subgraf

dan The. perbezaan dengan MATLAB ialah jika terdapat kesan empat subgraf, seperti:

MATLAB:

subplot(2,2,1)
subplot(2,2,2)
subplot(2,2,[3,4])
Python:

subplot(2,2,1)
subplot(2,2,2)
subplot(2,1,2)
kod:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np
 
 
# set up a figure twice as wide as it is tall
fig = plt.figure(figsize=plt.figaspect(0.5))
 
#===============
#  First subplot
#===============
# set up the axes for the first plot
ax = fig.add_subplot(2, 2, 1, projection=&#39;3d&#39;)
 
# plot a 3D surface like in the example mplot3d/surface3d_demo
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)
 
#===============
# Second subplot
#===============
# set up the axes for the second plot
ax = fig.add_subplot(2,1,2, projection=&#39;3d&#39;)
 
# plot a 3D wireframe like in the example mplot3d/wire3d_demo
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
 
plt.show()

Tambahan:

Penggunaan asas anotasi teks:

kod:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
 
 
fig = plt.figure()
ax = fig.gca(projection=&#39;3d&#39;)
 
# Demo 1: zdir
zdirs = (None, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;, (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10, 3, 8, 9, 1, 8)
 
for zdir, x, y, z in zip(zdirs, xs, ys, zs):
    label = &#39;(%d, %d, %d), dir=%s&#39; % (x, y, z, zdir)
    ax.text(x, y, z, label, zdir)
 
# Demo 2: color
ax.text(9, 0, 0, "red", color=&#39;red&#39;)
 
# Demo 3: text2D
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)
 
# Tweaking display region and labels
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
ax.set_xlabel(&#39;X axis&#39;)
ax.set_ylabel(&#39;Y axis&#39;)
ax.set_zlabel(&#39;Z axis&#39;)
 
plt.show()

[Cadangan berkaitan:

Tutorial video Python3 ]

Atas ialah kandungan terperinci Tutorial terperinci tentang melukis graf tiga dimensi dalam python. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:jb51.net. Jika ada pelanggaran, sila hubungi admin@php.cn Padam