import matplotlib.pyplot as plt
rows = 5
plt.figure(figsize=(6, 6))
for i in range(rows, 0, -1):
for j in range(rows - i, rows + i - 1):
plt.scatter(j, - (rows - i), s=800, c='red')
plt.xlim(-0.5, 2 * rows - 1.5)
plt.ylim(-rows + 0.5, 0.5)
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.title("Inverted Pyramid 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 allows us to create scatter plots.
2. Defining the Number of Rows
rows = 5
rows = 5: Controls the height of the inverted pyramid.
3. Creating the Figure
plt.figure(figsize=(6, 6))
Initializes a 6x6 inches plot.
Generating the Inverted Pyramid Shape
4. Looping to Generate the Pattern
for i in range(rows, 0, -1): # Loop from rows down to 1
for j in range(rows - i, rows + i - 1): # Controls the number of dots per row
plt.scatter(j, -(rows - i), s=800, c='red')
The outer loop (i) runs in reverse from rows down to 1, ensuring that the top row is widest and the bottom row is smallest.
The inner loop (j) determines how many dots are printed per row:
rows - i: Ensures proper horizontal spacing.
rows + i - 1: Expands outward as i decreases.
plt.scatter(j, -(rows - i), s=800, c='red') places red dots at calculated positions.
s=800: Controls the size of the dots.
-(rows - i): Ensures correct vertical placement.
Adjusting the Plot Appearance
5. Setting Axis Limits
plt.xlim(-0.5, 2 * rows - 1.5)
plt.ylim(-rows + 0.5, 0.5)
plt.xlim(-0.5, 2 * rows - 1.5): Ensures centered horizontal alignment.
plt.ylim(-rows + 0.5, 0.5): Ensures the entire inverted pyramid is visible.
6. Removing Axes and Adjusting Aspect Ratio
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.axis('off'): Hides grid lines and axis labels for a clean display.
plt.gca().set_aspect('equal', adjustable='datalim'): Maintains equal spacing between dots.
7. Adding a Title
plt.title("Inverted Pyramid Pattern Plot", fontsize=14)
Displays the title of the plot.
8. Displaying the Pattern
plt.show()
Renders and displays the inverted pyramid pattern.
0 Comments:
Post a Comment