Matplotlib 简明教程

Matplotlib - 3D Surface Plots

3D 表面绘图是一种可视化具有三个维度(长度、宽度和高度)的数据的方式。

A 3D surface plot is a way to visualize data that has three dimensions: length, width, and height.

想象一个有山丘和山谷的地貌,其中表面上的每个点都代表特定值。在 3D 表面绘图中,这些点在三维空间中绘出,创建一个显示数据如何随着不同位置而变化的表面。这就像查看数据的 3D 地图,其中表面的高度表示每个点的值。

Imagine a landscape with hills and valleys where each point on the surface represents a specific value. In a 3D surface plot, these points are plotted in a three-dimensional space, creating a surface that shows how the data varies across different positions. It is like looking at a three-dimensional map of the data, where the height of the surface represents the value of the data at each point.

3d surface plots1

3D Surface Plot in Matplotlib

在 Matplotlib 中,3D 表面绘图是多个点连接在一起类似于具有三维空间中特定区域的图形的可视化表示。我们可以使用“mpl_toolkits.mplot3d”模块中的 plot_surface() 函数在 Matplotlib 中创建 3D 表面绘图。它采用 X、Y 和 Z 坐标作为数组,并通过连接三个坐标来创建一个连续的图形。

In Matplotlib, a 3D surface plot is a visual representation of multiple points connected like a graph with a specific area in three-dimensional space. We can create a 3d surface plot in Matplotlib using the plot_surface() function in "mpl_toolkits.mplot3d" module. It takes the X, Y, and Z coordinates as arrays and creates a continuous graph by joining the three coordinates.

让我们首先绘制一个基本的 3D 曲面图。

Let’s start by drawing a basic 3D surface plot.

Basic 3D Surface Plot

Matplotlib 中的基本 3D 曲面图是表示三维图形的一种方式,具有 X、Y 和 Z 轴。坐标形成曲面,其中每个点的深度或高度(Z 轴)赋予该图三位形状。

A basic 3D surface plot in Matplotlib is way of representing a graph in three dimensions, with X, Y, and Z axes. The coordinates form a surface where height or depth (Z-axis) at each point gives the plot its three-dimensional shape.

在以下示例中,我们通过均匀间隔 X 和 Y 坐标来创建一个基本的 3D 曲面图,然后根据 X 和 Y 坐标的值找到 Z 坐标 −

In the following example, we are creating a basic 3D surface plot by evenly spacing the X and Y coordinates and then finding the Z coordinate based on the values of X and Y coordinates −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the basic 3D surface
ax.plot_surface(X, Y, Z, cmap='viridis')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Basic 3D Surface Plot')

# Displaying the plot
plt.show()

以下是上面代码的输出: -

Following is the output of the above code −

3d surface plots2

Parametric 3D Surface Plots

Matplotlib 中的参数 3D 曲面图使用数学方程在三维空间中定义图形。这些方程描述了 X、Y 和 Z 坐标值如何随着参数值的变化而变化。

Parametric 3D surface plots in Matplotlib use mathematical equations to define a graph in three-dimensional space. These equations describe how the values of X, Y, and Z coordinates changes with variations in parameter values.

在这里,我们通过相对于初始数据点 (u、v)、尺寸 ® 和厚度 (r) 参数化 X、Y 和 Z 坐标来创建一个参数 3D 曲面图。结果图显示了一个甜甜圈形状的曲面图 −

In here, we are creating a parametric 3D surface plot by parametrizing the X, Y, and Z coordinates with respect to initial data points (u, v), size ® and thickness (r). The resulting plot shows a donut-shaped surface plot −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Parametric equations for a torus
def torus_parametric(u, v, R=1, r=0.3):
   x = (R + r * np.cos(v)) * np.cos(u)
   y = (R + r * np.cos(v)) * np.sin(u)
   z = r * np.sin(v)
   return x, y, z

# Generating data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, 2 * np.pi, 100)
U, V = np.meshgrid(u, v)
X, Y, Z = torus_parametric(U, V)

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the parametric 3D surface
ax.plot_surface(X, Y, Z, cmap='plasma')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Parametric 3D Surface Plot (Torus)')

# Displaying the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

3d surface plots3

Multiple 3D Surface Plots

在 Matplotlib 中,来多个 3D 曲面图在三维空间中显示多个堆叠在一起的图形。每个图形的 X、Y 和 Z 坐标的值互不相同。

In Matplotlib, multiple 3D surface plots displays multiple graphs stacked on top of each other in a three-dimensional space. Each graph has a distinct value for the X, Y, and Z coordinates.

以下示例创建了两个堆叠在一起的 3D 曲面图。我们使用不同的方程创建两个不同的 3D 曲面图。结果图显示了具有不同颜色在不同平面上两个曲面图 −

The following example creates two 3D surface plots stacked on top of each other. We use different equations to create two distinct 3D surface plots. The resultant plot shows the two surface plots on different planes with different colors −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating data for two surfaces
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z1 = np.sin(np.sqrt(X**2 + Y**2))
Z2 = np.exp(-(X**2 + Y**2))

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the two surfaces
surf1 = ax.plot_surface(X, Y, Z1, cmap='viridis', alpha=0.7)
surf2 = ax.plot_surface(X, Y, Z2, cmap='plasma', alpha=0.7)

# Customize the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Multiple Surfaces in 3D Surface Plot')

# Adding a colorbar
fig.colorbar(surf1, ax=ax, orientation='vertical', shrink=0.5, aspect=20)

# Displaying the plot
plt.show()

执行上面的代码后,我们得到以下输出: -

After executing the above code, we get the following output −

3d surface plots4

Interpolated 3D Surface Plots

Matplotlib 中的插值 3D 曲面图有助于我们可视化其 X、Y 和 Z 坐标随机散布的图形。插值有助于填充缺少的数据点,以创建连续的图形。

Interpolated 3D surface plots in Matplotlib help us to visualize a graph whose X, Y, and Z coordinates are scattered randomly. Interpolation helps to fill in the missing data points to create a continuous graph.

现在,我们正在创建插值 3D 曲面图。我们为 X、Y 和 Z 坐标生成随机值,然后使用线性插值基于最近数据点估算缺少数据点值 −

Now, we are creating an interpolated 3D surface plots. We generate random values for the X, Y, and Z coordinates and then use linear interpolation to estimate the values of missing data points using nearest data points −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import griddata

# Creating irregularly spaced data
np.random.seed(42)
x = np.random.rand(100)
y = np.random.rand(100)
z = np.sin(x * y)

# Creating a regular grid
xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
xi, yi = np.meshgrid(xi, yi)

# Interpolating irregular data onto the regular grid
zi = griddata((x, y), z, (xi, yi), method='linear')

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D surface from irregular data using grid interpolation
ax.plot_surface(xi, yi, zi, cmap='viridis', edgecolor='k')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Surface Plot from Irregular Data (Grid Interpolation)')

# Displaying the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

3d surface plots5