Home > Article > Backend Development > How to Plot a Surface from a List of 3D Points in Matplotlib?
Surface Plotting in Matplotlib
When working with spatial data, generating surfaces can provide valuable insights. In Matplotlib, the plot_surface function is utilized for this purpose. However, it requires input in the form of 2D arrays, making it incompatible with a list of 3-tuples representing 3D points.
Data Transformation
To plot a surface from 3-tuples, we need to transform the data into the required format. Since the given data lacks any underlying function f(x, y), we must triangulate the points to create a surface.
Triangulation and Transformation
For the triangulation process, we can use the [triangulate_points](https://matplotlib.org/stable/gallery/mplot3d/triangulation_demo.html) function. It generates a list of triangles that connect the provided points, effectively creating a surface mesh.
Once triangulated, we can obtain the required 2D arrays for X, Y, and Z. These arrays represent the coordinates of the vertices for each triangle.
Plotting the Surface
With the transformed data, we can now invoke plot_surface:
<code class="python">import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection # List of 3-tuples representing points data = [(x1, y1, z1), (x2, y2, z2), ...] # Triangulate the points triangles = triangulate_points(data) # Extract 2D arrays for X, Y, and Z X, Y, Z = zip(*triangles) # Plot the surface fig = plt.figure() ax = fig.add_subplot(111, projection='3d') 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 script will generate a smooth surface that covers the given 3D points.
The above is the detailed content of How to Plot a Surface from a List of 3D Points in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!