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 obtain 3D colored surface via Python?
To create a 3D colored surface plot in Python, we use matplotlib's 3D plotting capabilities with numpy for data generation. The surface colors are mapped based on z-values using colormaps.
Steps to Create 3D Colored Surface
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Generate 3D data (z values) based on x and y coordinates.
Create a new figure or activate an existing figure.
Get the 3D axes using projection='3d'.
Create a surface plot with colormap.
Display the figure using show() method.
Example
Here's how to create a 3D colored surface plot ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-3, 3, 100)
y = np.cos(x)
x, y = np.meshgrid(x, y)
z = x ** 2 + y ** 2 - 2
fig = plt.figure()
ax = plt.axes(projection='3d')
surf = ax.plot_surface(x, y, z,
cmap=plt.get_cmap('hot'),
edgecolor='none')
plt.show()
The output shows a 3D surface where colors represent different z-values ?
[3D surface plot with hot colormap displayed]
Understanding the Code
The meshgrid() function creates coordinate matrices from coordinate vectors. The plot_surface() method renders the 3D surface with the 'hot' colormap, where red represents higher values and darker colors represent lower values.
Different Colormap Example
You can use different colormaps for various visual effects ?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z,
cmap='viridis',
alpha=0.8,
edgecolor='black',
linewidth=0.1)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Colored Surface with Viridis Colormap')
plt.colorbar(surf)
plt.show()
This creates a ripple effect surface with the viridis colormap and includes a colorbar legend ?
[3D surface plot with viridis colormap, labels, and colorbar displayed]
Conclusion
Creating 3D colored surfaces in Python requires numpy for data generation and matplotlib's 3D plotting. Use plot_surface() with different colormaps to visualize data relationships effectively.
