import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure(figsize=(6,7))
ax=fig.add_subplot(111,projection='3d')
x=np.linspace(-10,10,200)
y=np.linspace(-10,10,200)
x,y=np.meshgrid(x,y)
r=np.sqrt(x**2+y**2)
z=np.sin(r)/r
z[r==0]=1
surf=ax.plot_surface(x,y,z,cmap='ocean',edgecolor='none')
ax.set_title('OceanRipple Pattern using Python',fontsize=16)
ax.set_xlabel('X Axis')
ax.set_xlabel('Y Axis')
ax.set_zlabel('Wave Height')
fig.colorbar(surf,shrink=0.5,aspect=5)
plt.tight_layout()
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 is used for
numerical operations, especially arrays and math functions.
matplotlib.pyplot
is used for plotting graphs.
mpl_toolkits.mplot3d.Axes3D
enables 3D plotting within matplotlib.
2.
Creating the 3D Figure and Axes
fig =
plt.figure(figsize=(10, 7))
ax =
fig.add_subplot(111, projection='3d')
fig =
plt.figure(figsize=(10, 7)): Initializes a new figure with size 10x7 inches.
add_subplot(111,
projection='3d'): Adds a 3D subplot (1 row, 1 column, 1 plot) to the figure.
3.
Generating a Grid for X and Y Coordinates
x =
np.linspace(-10, 10, 200)
y =
np.linspace(-10, 10, 200)
x, y =
np.meshgrid(x, y)
np.linspace(-10,
10, 200): Creates 200 evenly spaced values between -10 and 10.
np.meshgrid(x, y):
Converts the 1D arrays into 2D coordinate grids for X and Y, used for surface
plotting.
4.
Defining the Ocean Ripple Pattern (Z Values)
r = np.sqrt(x**2 +
y**2)
z = np.sin(r) / r
z[r == 0] = 1
r = np.sqrt(x**2 +
y**2): Computes the radial distance from the origin (like a circular ripple).
z = np.sin(r) / r:
Defines a ripple pattern based on the sinc function, which gives a wave-like
structure.
z[r == 0] = 1:
Handles the case where r = 0 to avoid division by zero (since sin(0)/0 is
undefined but limit = 1).
5.
Plotting the Surface
surf =
ax.plot_surface(x, y, z, cmap='ocean', edgecolor='none')
plot_surface: Plots
a 3D surface based on X, Y, Z values.
cmap='ocean':
Applies a blue-ish colormap to simulate water.
edgecolor='none':
Removes gridlines for a smooth surface look.
6.
Adding Title and Axis Labels
ax.set_title('OceanRipples
pattern using python', fontsize=16)
ax.set_xlabel('X
Axis')
ax.set_ylabel('Y
Axis')
ax.set_zlabel('Wave
Height')
Sets the main title
and axis labels to describe the 3D plot.
7.
Adding a Color Bar
fig.colorbar(surf,
shrink=0.5, aspect=5)
Adds a color scale
to the side of the plot to show what values each color represents.
shrink and aspect
control its size and proportions.
8.
Final Touch & Display
plt.tight_layout()
plt.show()
tight_layout():
Adjusts layout to avoid overlap.
show(): Displays
the final plot.
0 Comments:
Post a Comment