import matplotlib.pyplot as plt
rows = 5
cols = 5
plt.figure(figsize=(6, 6))
for i in range(rows):
for j in range(cols):
if i == 0 or i == rows - 1 or j == 0 or j == cols - 1:
plt.scatter(j, -i, s=800, c='orange')
plt.xlim(-0.5, cols - 0.5)
plt.ylim(-rows + 0.5, 0.5)
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.title("Hollow Square Pattern Plot", fontsize=14)
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Importing Matplotlib
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, which is used to create plots.
2. Defining the Dimensions of the Square
rows = 5
cols = 5
rows = 5: Sets the height of the square.
cols = 5: Sets the width of the square.
3. Initializing the Plot
plt.figure(figsize=(6, 6))
Creates a figure with a size of 6x6 inches.
Generating the Hollow Square
4. Using Nested Loops to Plot the Dots
for i in range(rows):
for j in range(cols):
if i == 0 or i == rows - 1 or j == 0 or j == cols - 1:
plt.scatter(j, -i, s=800, c='red')
The outer loop (i) iterates over the rows.
The inner loop (j) iterates over the columns.
The if condition ensures that only border points are plotted:
i == 0 → Top row
i == rows - 1 → Bottom row
j == 0 → Left column
j == cols - 1 → Right column
plt.scatter(j, -i, s=800, c='red') places a red dot at the coordinates (j, -i).
s=800: Controls the size of the dots.
-i: Ensures that rows go downward.
Adjusting the Plot Appearance
5. Setting Axis Limits
plt.xlim(-0.5, cols - 0.5)
plt.ylim(-rows + 0.5, 0.5)
plt.xlim(-0.5, cols - 0.5): Ensures the square is centered horizontally.
plt.ylim(-rows + 0.5, 0.5): Ensures the square is fully visible vertically.
6. Removing Axes and Adjusting Aspect Ratio
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.axis('off'): Removes grid lines and axis labels for a clean display.
plt.gca().set_aspect('equal', adjustable='datalim'): Ensures equal spacing between points.
7. Adding a Title
plt.title("Hollow Square Pattern Plot", fontsize=14)
Displays the title of the plot.
8. Displaying the Pattern
plt.show()
Renders and displays the hollow square pattern.
0 Comments:
Post a Comment