Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the equivalent of Matlab's surf(x,y,z,c) in Matplotlib?
In MATLAB, surf(x,y,z,c) creates a 3D surface plot where the color is determined by the matrix c. In Matplotlib, the equivalent functionality is achieved using plot_surface() with appropriate parameters.
Basic Surface Plot
The simplest equivalent uses plot_surface() with a colormap ?
import matplotlib.pyplot as plt import numpy as np # Set figure properties plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create figure and 3D axis fig = plt.figure() ax = fig.add_subplot(projection='3d') # Generate data for a sphere u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:20j] x = np.cos(u) * np.sin(v) y = np.sin(u) * np.sin(v) z = np.cos(v) # Create surface plot with colormap surface = ax.plot_surface(x, y, z, cmap='YlGnBu_r') plt.show()
Surface Plot with Custom Color Data
To specify custom colors like MATLAB's c parameter, use the facecolors argument ?
import matplotlib.pyplot as plt
import numpy as np
# Create figure and 3D axis
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection='3d')
# Generate grid data
x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# Custom color data (equivalent to MATLAB's 'c' parameter)
C = np.sqrt(X**2 + Y**2)
# Create surface with custom colors
surface = ax.plot_surface(X, Y, Z, facecolors=plt.cm.viridis(C/C.max()), alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Surface Plot with Custom Colors')
plt.show()
Comparison Table
| MATLAB | Matplotlib Equivalent | Description |
|---|---|---|
surf(x,y,z) |
plot_surface(x,y,z) |
Basic surface plot |
surf(x,y,z,c) |
plot_surface(x,y,z, facecolors=colormap(c)) |
Surface with custom colors |
colormap |
cmap parameter |
Color scheme selection |
Key Parameters
cmap ? Colormap for automatic coloring based on Z values
facecolors ? Custom color array for each face (equivalent to MATLAB's 'c')
alpha ? Transparency level (0.0 to 1.0)
shade ? Enable/disable shading effects
Conclusion
Matplotlib's plot_surface() provides equivalent functionality to MATLAB's surf(). Use cmap for automatic coloring or facecolors to specify custom colors like MATLAB's c parameter.
