Home > Backend Development > Python Tutorial > How to Create a Surface Plot in Matplotlib with a List of 3D Points?

How to Create a Surface Plot in Matplotlib with a List of 3D Points?

Mary-Kate Olsen
Release: 2024-10-26 14:55:30
Original
987 people have browsed it

How to Create a Surface Plot in Matplotlib with a List of 3D Points?

Surface Plots in Matplotlib

When creating a surface plot, the plot_surface function requires 2D arrays as arguments to represent the points in 3D space. However, if you only have a list of 3D points, there are specific considerations to take.

Triangulating Point Clouds

For a list of 3D points, plot_surface cannot be used directly due to the ambiguity in triangulating the points into a surface. Matplotlib does not provide a method to automatically triangulate points into a surface.

Alternative Approach: Grid-Based Surface

If you do not have a function representing the surface, you can generate a grid-based surface using a function like fun(x, y). In this approach, you define a meshgrid of points and compute the corresponding z-values using the given function.

<code class="python">import numpy as np
import matplotlib.pyplot as plt

# Define the function
def fun(x, y):
    return x**2 + y

# Create a meshgrid
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)

# Compute the z-values
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)

# Create the surface plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)</code>
Copy after login

This approach allows you to create a smooth surface that passes through the given 3D points and covers the entire extent of the grid.

The above is the detailed content of How to Create a Surface Plot in Matplotlib with a List of 3D Points?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template