import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.heaviside(np.sin(X) * np.cos(Y), 0.5)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title("Step Function Grid")
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Importing Required Libraries
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
matplotlib.pyplot is used for plotting.
mpl_toolkits.mplot3d.Axes3D enables 3D plotting support.
numpy is used for numerical operations, especially arrays and math functions.
2. Creating the Grid
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 points between
-5 and 5 for both x and y.
np.meshgrid(x, y) creates 2D coordinate matrices from the 1D x and y arrays. X and Y are 2D arrays representing all combinations of x and y.
3. Defining the Step Function Surface
Z = np.heaviside(np.sin(X) * np.cos(Y), 0.5)
This defines the Z values (heights) of the surface.
np.sin(X) * np.cos(Y) creates a pattern of values
based on sine and cosine waves.
np.heaviside(..., 0.5) converts those values into
step-like (binary) outputs:
Returns 1 where the argument is positive,
0 where it's negative,
0.5 exactly at zero (by definition here).
This creates a checkerboard-like grid of 0s and 1s.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.figure() initializes a new figure.
add_subplot(111, projection='3d') adds one 3D
subplot to the figure.
ax.plot_surface(X, Y, Z, cmap='viridis')
plot_surface() creates a 3D surface plot.
X, Y, Z define the surface coordinates.
cmap='viridis' sets the color gradient for the
surface.
ax.set_title("Step Function Grid")
plt.show()
set_title() adds a title to the plot.
plt.show() renders and displays the plot window.


0 Comments:
Post a Comment