Considering a list of 3-tuples denoting points in 3D space, the task is to generate a surface covering these points.
Using plot_surface from the mplot3d package requires input data in the form of 2D arrays for X, Y, and Z. To transform the given data structure, there are certain considerations to make.
In the case of surfaces, unlike line plots, you need to define a grid covering the domain using 2D arrays. When working with only a list of 3D points, triangulation becomes essential. This is because there are multiple possible triangulations for a given point cloud.
For a smooth surface, the following approach can be taken:
<code class="python">import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import random def fun(x, y): return x**2 + y fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = y = np.arange(-3.0, 3.0, 0.05) X, Y = np.meshgrid(x, y) zs = np.array(fun(np.ravel(X), np.ravel(Y))) Z = zs.reshape(X.shape) ax.plot_surface(X, Y, Z) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show()</code>
This code defines a grid using meshgrid, generates the corresponding Z values, and creates the surface plot using plot_surface. The resulting surface provides a smooth representation of the underlying data.
The above is the detailed content of How to Create Smooth 3D Surfaces from Scattered Data Using Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!