import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x=np.linspace(-5,5,100)
y=np.linspace(-5,5,100)
x,y=np.meshgrid(x,y)
z=np.sin(np.sqrt(x**2+y**2))
fig=plt.figure(figsize=(6,6))
ax=fig.add_subplot(111,projection='3d')
surface=ax.plot_surface(x,y,z,cmap='terrain',edgecolor='none')
fig.colorbar(surface)
ax.set_xlabel('X (Longitude)')
ax.set_ylabel('Y(Latitude)')
ax.set_zlabel('Z(Elevation)')
ax.set_title('3D Topographical pattern')
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
numpy (np): Used for numerical operations like
creating arrays and applying mathematical functions.
matplotlib.pyplot (plt): Used for plotting graphs and figures.
mpl_toolkits.mplot3d: Adds support for 3D plotting using Axes3D.
2. Creating Grid Data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
np.linspace(-5, 5, 100): Creates 100 evenly spaced
points from -5 to 5 for both x and y axes.
np.meshgrid(x, y): Creates a 2D grid of all combinations of x and y — needed for surface plotting.
3. Defining the Elevation (Z-values)
z = np.sin(np.sqrt(x**2 + y**2))
This creates elevation data using a sine wave based
on the distance from the origin (0,0). It looks like ripples or waves radiating
from the center.
Formula breakdown:
x**2 + y**2: Computes the square of the distance.
np.sqrt(...): Takes the square root → gives radial
distance.
np.sin(...): Applies the sine function to generate
oscillations.
4. Creating the Plot Figure
fig = plt.figure(figsize=(10, 7))
Initializes a new figure window.
figsize=(10, 7): Sets the width and height of the
figure in inches.
5. Adding a 3D Subplot
ax = fig.add_subplot(111, projection='3d')
Adds a 3D plotting area to the figure.
111 = 1 row, 1 column, 1st subplot.
projection='3d': Tells matplotlib to enable 3D
plotting for this subplot.
6. Plotting the 3D Surface
surface = ax.plot_surface(x, y, z, cmap='terrain',
edgecolor='none')
Creates the 3D surface from x, y, and z data.
cmap='terrain': Applies a terrain color map to
simulate real-world elevation colors (greens, browns, etc.).
edgecolor='none': Removes grid lines for a cleaner
look.
7. Adding a Color Bar
fig.colorbar(surface)
Adds a color bar beside the plot.
Shows how colors map to elevation values (Z-axis).
8. Labeling the Axes
ax.set_xlabel('X (Longitude)')
ax.set_ylabel('Y (Latitude)')
ax.set_zlabel('Z (Elevation)')
Labels each axis for clarity:
X: "Longitude"
Y: "Latitude"
Z: "Elevation"
9. Setting the Plot Title
ax.set_title('3D Topographical Plot')
Adds a descriptive title to the top of the plot.
10. Displaying the Plot
plt.show()
Renders the plot in a window or notebook.
Allows for interactive rotation, zoom, and pan if
run in a GUI or Jupyter Notebook.


0 Comments:
Post a Comment