import numpy as np
import matplotlib.pyplot as plt
def generate_tree_rings(num_rings=20, max_radius=10, noise_factor=0.2):
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_xlim(-max_radius, max_radius)
ax.set_ylim(-max_radius, max_radius)
ax.set_aspect('equal')
ax.axis('off')
for i in range(1, num_rings + 1):
radius = (i / num_rings) * max_radius
theta = np.linspace(0, 2 * np.pi, 500)
r_noise = radius + noise_factor * np.sin(5 * theta) * np.random.uniform(0.5, 1.5)
x = r_noise * np.cos(theta)
y = r_noise * np.sin(theta)
ax.plot(x, y, color='saddlebrown', lw=1)
plt.title("Tree Rings Pattern", fontsize=14, fontweight='bold')
plt.show()
generate_tree_rings()
#source code --> clcoding.com
Code Explanation:
Step 1: Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
NumPy (np): Used for mathematical operations, especially creating a grid of points.
Matplotlib (plt): Used for visualization, specifically to create a contour plot of the ripple pattern.
Step 2: Creating a Grid of Points
x = np.linspace(-5, 5, 400) # X-axis range
y = np.linspace(-5, 5, 400) # Y-axis range
X, Y = np.meshgrid(x, y) # Create a coordinate grid
np.linspace(-5, 5, 400): Creates 400 evenly spaced points between -5 and 5 for both the X and Y axes.
np.meshgrid(x, y): Converts these 1D arrays into 2D coordinate matrices, so we can compute values at every point in a 2D space.
Step 3: Defining the Ripple Effect
R = np.sqrt(X**2 + Y**2) # Compute radial distance from the center
Z = np.sin(5 * R) / (1 + R) # Apply a damped sine wave function
R = np.sqrt(X**2 + Y**2):
Computes the radial distance of each point from the origin (0,0).
This ensures that waves radiate outward from the center.
Z = np.sin(5 * R) / (1 + R):
sin(5 * R): Generates oscillations that form the ripple pattern.
/(1 + R): Damps the waves so they fade out as they move away from the center.
Step 4: Plotting the Ripple Effect
plt.figure(figsize=(6, 6)) # Set figure size
plt.contourf(X, Y, Z, cmap='Blues') # Create filled contour plot
plt.colorbar(label='Wave Intensity') # Add color legend
plt.axis('off') # Remove axes for a clean look
plt.title("Water Ripple Pattern") # Set title
plt.show() # Display the plot
plt.contourf(X, Y, Z, cmap='Blues'):
Creates smooth color-filled contours based on Z values.
cmap='Blues': Uses blue shades to resemble water ripples.
plt.colorbar(label='Wave Intensity'):
Adds a color legend indicating the intensity of the waves.
plt.axis('off'):
Removes axes to give a clean water effect.
plt.show():
Displays the final ripple effect.
0 Comments:
Post a Comment