import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(x) * np.cos(y)
checkerboard = ((np.floor(x) + np.floor(y)) % 2) == 0
colors = np.zeros(x.shape + (3,))
colors[checkerboard] = [1, 1, 1]
colors[~checkerboard] = [0, 0, 0]
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, facecolors=colors, rstride=1, cstride=1)
ax.set_title("3D Checkerboard Surface", fontsize=14)
ax.set_box_aspect([1, 1, 0.5])
ax.axis('off')
plt.tight_layout()
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy (as np): Used for creating grids and
performing numerical calculations (like sin, cos, floor, etc.).
matplotlib.pyplot (as plt): Used for plotting graphs
and rendering the 3D surface.
2. Create Grid Coordinates (x, y)
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
np.linspace(-5, 5, 100): Generates 100 evenly spaced
values from -5 to 5 for both x and y.
np.meshgrid(x, y): Creates 2D grids from the 1D x
and y arrays — necessary for plotting surfaces.
3. Define Surface Height (z values)
z = np.sin(x) * np.cos(y)
This creates a wavy surface using a trigonometric
function.
Each (x, y) point gets a z value, forming a 3D
landscape.
4. Generate Checkerboard Pattern
checkerboard = ((np.floor(x) + np.floor(y)) % 2) ==
0
np.floor(x): Takes the floor (integer part) of each
x and y coordinate.
Adds the floored x + y, and checks if the sum is
even (i.e., divisible by 2).
If so → True (white square), else → False (black
square).
This results in a checkerboard-like boolean mask.
5. Assign Colors to Checkerboard
colors = np.zeros(x.shape + (3,))
colors[checkerboard] = [1, 1, 1]
colors[~checkerboard] = [0, 0, 0]
colors = np.zeros(x.shape + (3,)): Initializes an
array for RGB colors (shape: rows × cols × 3).
For True cells in checkerboard, assign white [1, 1,
1].
For False cells, assign black [0, 0, 0].
6. Set Up 3D Plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
Creates a figure and a 3D subplot using
projection='3d'.
7. Plot the Checkerboard Surface
ax.plot_surface(x, y, z, facecolors=colors,
rstride=1, cstride=1)
Plots the 3D surface using x, y, z data.
facecolors=colors: Applies the checkerboard color
pattern.
rstride and cstride: Row/column steps for rendering
— set to 1 for full resolution.
8. Customize the View
ax.set_title("3D Checkerboard Surface",
fontsize=14)
ax.set_box_aspect([1, 1, 0.5])
ax.axis('off')
set_title(): Sets the plot title.
set_box_aspect(): Controls aspect ratio: x:y:z =
1:1:0.5 (compressed z).
axis('off'): Hides axis ticks and labels for a clean
look.
9. Render the Plot
plt.tight_layout()
plt.show()
tight_layout(): Adjusts spacing to prevent overlap.
show(): Renders the 3D checkerboard surface.


0 Comments:
Post a Comment