import matplotlib.pyplot as plt
import numpy as np
rows,cols=5,5
x=np.arange(cols)
y=np.arange(rows)
X,Y=np.meshgrid(x,y)
X=X.flatten()
Y=Y.flatten()
fig,ax=plt.subplots(figsize=(6,6))
ax.scatter(X,Y,marker='*',s=300,color='gold',edgecolor='black')
ax.set_xlim(-1,cols)
ax.set_ylim(-1,rows)
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
plt.show()
#source code --> clcoding.com
Code Explanation:
Step 1: Import Required Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot (plt): Used for creating plots and visualizations.
numpy (np): Used for numerical operations, like generating coordinate grids.
Step 2: Define the Grid Size
rows, cols = 5, 5
Sets the number of rows and columns in the star pattern.
The grid will have 5 rows and 5 columns, making a 5x5 arrangement.
Step 3: Create X and Y Coordinates
x = np.arange(cols) # Creates an array [0, 1, 2, 3, 4] for x-coordinates
y = np.arange(rows) # Creates an array [0, 1, 2, 3, 4] for y-coordinates
X, Y = np.meshgrid(x, y)
np.arange(cols): Generates an array [0, 1, 2, 3, 4] for the x-coordinates.
np.arange(rows): Generates an array [0, 1, 2, 3, 4] for the y-coordinates.
np.meshgrid(x, y): Creates a grid of (X, Y) coordinate pairs where each star will be placed.
Step 4: Convert 2D Arrays to 1D Lists
X = X.flatten()
Y = Y.flatten()
Converts X and Y from 2D arrays into 1D arrays.
This is needed because scatter() requires 1D lists of x and y coordinates.
Step 5: Create a Figure and Axis
fig, ax = plt.subplots(figsize=(6, 6))
Creates a figure (fig) and axis (ax) for the plot.
figsize=(6,6) sets the plot size to 6x6 inches.
Step 6: Plot Stars using scatter()
ax.scatter(X, Y, marker='*', s=300, color='gold', edgecolors='black')
scatter(X, Y, marker='*'): Plots stars (*) at each (X, Y) coordinate.
s=300: Controls the size of each star.
color='gold': Makes the stars golden.
edgecolors='black': Adds black outlines around the stars.
Step 7: Adjust Axis Limits
ax.set_xlim(-1, cols) # Limits the x-axis from -1 to 5 (adds padding)
ax.set_ylim(-1, rows) # Limits the y-axis from -1 to 5 (adds padding)
Sets x-axis from -1 to cols (5) to provide a little spacing.
Sets y-axis from -1 to rows (5) to prevent crowding.
Step 8: Remove Unnecessary Axes Information
ax.set_xticks([]) # Removes x-axis tick marks
ax.set_yticks([]) # Removes y-axis tick marks
ax.set_frame_on(False) # Hides the axis border
Removes tick marks (set_xticks([]), set_yticks([])) to make the grid cleaner.
Hides the border (set_frame_on(False)) to focus only on the stars.
Step 9: Display the Plot
plt.show()
Displays the star pattern on the screen.
0 Comments:
Post a Comment