Matplotlib 3D drawing, this one is enough
This blog will introduce you to 3D mapping using the mplot3d toolkit, which supports simple 3D graphics, including surfaces, wire-frames, scatter plots, and bar plots.
1. The rendering
1.1 3D line effect drawing
The 3D line graph looks like this:You can customize the color of the line and the style of the dots.
1.2 3D scatter effect diagram
The 3D scatter plot (colored to give a depth appearance) looks like this:
1.3 3D random color scatter effect diagram
The effect of 3D random color scatter diagram is as follows:
1.4 3D scatter effect pictures of different Mark points
The effect of different mark points on 3D official scatter chart is as follows:
1.5 3D wireframes effect drawing
The 3D wireframes look like this:
1.6 3D opaque surface rendering
The opacity of the 3D surface is as follows:
1.7 3D transparent rendering of curved surface
The 3D surface is transparent as follows:
2. The source code
# matplotlib 3D drawing
The # 3D axis (belonging to the Axes3D class) is created by passing the projection=" 3D "keyword argument to Figure. Add_subplot:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100)
y = np.random.randint(0.300.100)
z = np.random.randint(0.200.100)
# 3 d map
def line_3d() :
# line
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# c color, marker: Style * snowflake
ax.plot(xs=x, ys=y, zs=z, c="y", marker="*")
plt.show()
# 3D scatter plot
def scatter_3d() :
# a scatter diagram
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# s: Size of marker marker
# c: Color can be a single, can be a sequence
# depthShade: Whether to color scatter marks to give a deep appearance. Each call to Scatter () performs its depth shading independently.
# marker: style
ax.scatter(xs=x, ys=y, zs=0, zdir='z', s=30, c="g", depthshade=True, cmap="jet", marker="^")
plt.show()
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
# 3D random color scatter plot
def scatter_random_color_3d() :
# Random color scatter plot
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# c: Color can be a single, can be a sequence
# 'b' blue, g 'green, R' red, c 'cyan
# 'm' magenta, 'y' yellow, 'k' black, 'w' white
colors = ['b'.'g'.'r'.'c'.'m'.'y'.'k'.'w']
c = np.repeat(colors, 15)[:100]
ax.scatter(xs=x, ys=y, zs=0, zdir='z', s=30, c=c, depthshade=True, cmap="jet", marker="^")
plt.show()
# demo sample
# Set the seed to reproduce random values
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
n = 100
For each style, draw n random points
X in [23, 32], y in [0, 100], z in [zlow, zhigh]
for m, zlow, zhigh in [('o', -50, -25), (A '^', -30, -5)]:
xs = randrange(n, 23.32)
ys = randrange(n, 0.100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
# wireframes
def wireframe_3d() :
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x = np.random.randint(-30, high=30, size=(50,)).reshape((25.2))
y = np.random.randint(-30, high=30, size=(50,)).reshape((25.2))
z = np.zeros(50).reshape((25.2))
# c: color
# 'b' blue, g 'green, R' red, c 'cyan
# 'm' magenta, 'y' yellow, 'k' black, 'w' white
ax.plot_wireframe(x, y, z, color='m')
plt.show()
# demo sample
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
Get test data
X, Y, Z = axes3d.get_test_data(0.05)
Draw basic wireframes
ax.plot_wireframe(X, Y, Z, color='c', rstride=10, cstride=10)
plt.show()
By default, it will be shaded with solid colors, but it also supports color mapping by providing cMAP parameters.
Both # rcount and ccount kwargs default to 50, which determines the maximum number of samples to use in each direction. If the input data is large, it is downsampled (by slicing) to these points.
# To maximize the rendering speed, set the rstride and cstride to the divisor of row number minus 1 and column number minus 1, respectively. For example, given 51 rows, the rstride can be any divisor of 50.
# Again, setting rstride and cstride equal to 1 (or rcount and ccount equal to the number of rows and columns) can be used to optimize the path.
def surface_3d() :
# 3D Surface (Color Map) Demo Draws 3D surfaces colored with warm and cold color maps. Make surfaces opaque by using antialiased=False.
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
# Build 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)
# Draw a surface diagram
# Draw 3D surfaces colored with warm and cold color maps. Make surfaces opaque by using antialiased=False.
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))
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}')
Add a color bar chart to show the range of colors
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
# Draw a surface diagram
# Draw 3D surfaces colored with warm and cold color maps. Make surfaces transparent by using antialiased=True.
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=True)
# Customize the Z-axis
ax.set_zlim(-1.01.1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}')
Add a color bar chart to show the range of colors
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
# Triangular surface diagram
def tri_surface_3d() :
n_radii = 8
n_angles = 36
# set the radius and Angle as an arithmetic array (omit radius r=0 to eliminate duplication)
# start, stop, n, endpoint The default endpoint is True with stop, False with no stop
radii = np.linspace(0.125.1.0, n_radii)
angles = np.linspace(0.2 * np.pi, n_angles, endpoint=False)[..., np.newaxis]
Convert polar coordinates to Cartesian coordinates (x, y)
# (0,0) is added manually at this stage so that points in the (x, y) plane are not repeated
x = np.append(0, (radii * np.cos(angles)).flatten())
y = np.append(0, (radii * np.sin(angles)).flatten())
# Compute Z to generate pringle surface pringle surface
z = np.sin(-x * y)
ax = plt.figure().add_subplot(projection='3d')
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
plt.show()
# 3 d map
line_3d()
# 3D scatter plot
scatter_3d()
# 3D random color scatter plot
scatter_random_color_3d()
# wireframes
wireframe_3d()
By default, it will be shaded with solid colors, but it also supports color mapping by providing cMAP parameters.
surface_3d()
# Triangular surface diagram
tri_surface_3d()
Copy the code
reference
- Matplotlib.org/stable/tuto…