Matplotlib – create a 3D surface plot

Here’s an code example using Matplotlib to create a 3D surface plot of a mathematical function.

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_title('3D Surface Plot of sin(sqrt(x^2 + y^2))')

# Add a color bar

# Show the plot
Code Explanation
  • We define a mathematical function f(x, y) = sin(sqrt(x^2 + y^2)).
  • We generate x and y values using np.linspace() and create a grid of points using np.meshgrid().
  • We calculate the corresponding z values (Z) using the defined function.
  • We create a 3D plot using Matplotlib with the projection='3d' argument.
  • We plot the surface using ax.plot_surface().
  • We customize the plot by adding labels, a title, and a color bar.
  • Finally, we display the plot using

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 �(�,�)=sin⁡(�2+�2)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.