This Python script demonstrates how to create a 3D surface plot using Matplotlib and NumPy.
It defines a mathematical function, f(x,y) = sin(x2 + y2), and generates a grid of x and y values. The function values are then computed to form a 3D surface. The plot is created using Matplotlib’s plot_surface function with a color map for better visualization.
This technique is useful for visualizing mathematical functions, terrain models, and scientific data.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the mathematical function to plot
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2))
# Generate x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
# Customize the plot
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Surface Plot of sin(sqrt(x^2 + y^2))')
# Add a color bar
fig.colorbar(surf)
# Show the plot
plt.show()
f(x, y) = sin(sqrt(x^2 + y^2))
.np.linspace()
and create a grid of points using np.meshgrid()
.projection='3d'
argument.ax.plot_surface()
.plt.show()
.This code example creates a visually appealing 3D surface plot of the mathematical function using Matplotlib’s advanced functionalities.
The output of the above code example is a 3D surface plot of the mathematical function f(x,y) = sin(x2 + y2). The plot will show a surface that oscillates smoothly with peaks and valleys, resembling a mountain range or a wave pattern.
The plot will have labeled axes (X, Y, Z) and a title (“3D Surface Plot of sin(sqrt(x^2 + y^2))”). Additionally, a color bar will be displayed on the side of the plot, indicating the values of the function corresponding to different colors on the surface.
The actual appearance of the plot may vary depending on the specific settings of your Matplotlib environment, such as the default colormap and the aspect ratio of the plot window.