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
How to change the color and add grid lines to a Python Matplotlib surface plot?
To change the color and add grid lines to a Python Matplotlib surface plot, you can customize the plot_surface() method with color parameters and edge properties. This creates visually appealing 3D visualizations with clear grid patterns.
Steps to Create a Colored Surface Plot with Grid Lines
Import required libraries:
numpy,matplotlib.pyplot, andAxes3DSet figure size and layout parameters
Create coordinate arrays using
numpy.meshgrid()Calculate height values for the surface
Create 3D axes and plot surface with color and grid customization
Example
Here's how to create a surface plot with custom colors and visible grid lines ?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create coordinate arrays
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y)
# Calculate height values
h = np.sin(x) * np.cos(y)
# Create 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot surface with custom colors and grid lines
ax.plot_surface(x, y, h,
rstride=10, cstride=10, # Grid density
color='orangered', # Surface color
edgecolors='yellow', # Grid line color
linewidth=0.6, # Grid line thickness
alpha=0.8) # Surface transparency
plt.show()
Key Parameters for Customization
| Parameter | Purpose | Example Values |
|---|---|---|
color |
Sets surface color | 'orangered', 'blue', '#FF5733' |
edgecolors |
Sets grid line color | 'yellow', 'black', 'white' |
linewidth |
Controls grid line thickness | 0.1 to 2.0 |
alpha |
Surface transparency | 0.0 (transparent) to 1.0 (opaque) |
Alternative Color Schemes
You can experiment with different color combinations for various visual effects ?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create data
x = np.arange(-3, 3, 0.2)
y = np.arange(-3, 3, 0.2)
x, y = np.meshgrid(x, y)
z = x**2 + y**2
fig = plt.figure(figsize=(10, 4))
# Blue surface with white grid
ax1 = fig.add_subplot(121, projection='3d')
ax1.plot_surface(x, y, z, color='lightblue', edgecolors='white', linewidth=0.3)
ax1.set_title('Blue with White Grid')
# Green surface with black grid
ax2 = fig.add_subplot(122, projection='3d')
ax2.plot_surface(x, y, z, color='lightgreen', edgecolors='black', linewidth=0.5)
ax2.set_title('Green with Black Grid')
plt.tight_layout()
plt.show()
Conclusion
Use the color and edgecolors parameters in plot_surface() to customize surface appearance. Adjust linewidth to control grid visibility and alpha for transparency effects.
