import matplotlib.pyplot as plt
rows = 5
plt.figure(figsize=(6, 6))
for i in range(rows):
for j in range(rows - i - 1, rows + i):
plt.scatter(j, -i, s=800, c='purple')
for i in range(rows - 2, -1, -1):
for j in range(rows - i - 1, rows + i):
plt.scatter(j, -(2 * rows - i - 2), s=800, c='purple')
plt.xlim(-0.5, 2 * rows - 1.5)
plt.ylim(-2 * rows + 1.5, 0.5)
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.title("Diamond 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 plots.
2. Setting the Number of Rows
rows = 5
The variable rows controls the height of the upper half of the diamond.
3. Creating the Figure
plt.figure(figsize=(6, 6))
Initializes a figure with dimensions 6x6 inches.
Generating the Diamond Shape
The diamond consists of two triangular halves:
Upper half (top to middle).
Lower half (middle to bottom).
4. Creating the Upper Part of the Diamond
for i in range(rows):
for j in range(rows - i - 1, rows + i):
plt.scatter(j, -i, s=800, c='red')
The outer loop (i) iterates over the rows.
The inner loop (j) controls the number of dots per row.
The range rows - i - 1 to rows + i ensures that dots expand outward as i increases.
plt.scatter(j, -i, s=800, c='red') places red dots at calculated positions.
5. Creating the Lower Part of the Diamond
for i in range(rows - 2, -1, -1):
for j in range(rows - i - 1, rows + i):
plt.scatter(j, -(2 * rows - i - 2), s=800, c='red')
The outer loop (i) iterates in reverse to form the lower half.
The inner loop (j) places dots in a shrinking pattern.
-(2 * rows - i - 2) correctly positions dots below the center.
Adjusting the Plot Appearance
6. Setting Axis Limits
plt.xlim(-0.5, 2 * rows - 1.5)
plt.ylim(-2 * rows + 1.5, 0.5)
plt.xlim(-0.5, 2 * rows - 1.5): Ensures the diamond is centered horizontally.
plt.ylim(-2 * rows + 1.5, 0.5): Ensures the full diamond is visible vertically.
7. 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 dots.
8. Adding a Title
plt.title("Diamond Pattern Plot", fontsize=14)
Displays the title of the plot.
9. Displaying the Pattern
plt.show()
Renders and displays the diamond pattern