import matplotlib.pyplot as plt
rows = 5
plt.figure(figsize=(6, 6))
for i in range(rows):
for j in range(i + 1):
x = j - i / 2
y = -i
plt.scatter(x, y, s=500, c='blue')
plt.xlim(-rows / 2, rows / 2)
plt.ylim(-rows, 1)
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.title("Equilateral Triangle Pattern Plot", fontsize=14)
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Importing Required Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot → Used for plotting the pattern.
numpy → Imported but not used in this code. It can be removed.
2. Defining the Number of Rows
rows = 5
Defines the height of the equilateral triangle as 5 rows.
3. Creating the Figure
plt.figure(figsize=(6, 6))
Creates a figure of size 6x6 inches to display the pattern properly.
4. Generating the Equilateral Triangle Pattern Using Nested Loops
for i in range(rows): # Loops through each row (i)
for j in range(i + 1): # Increasing dots in each row
x = j - i / 2 # Centering the triangle
y = -i # Y-coordinates for arranging rows from top to bottom
plt.scatter(x, y, s=500, c='blue') # Plots a blue dot
Outer loop (i) → Controls the number of rows.
Inner loop (j) → Controls the number of dots per row:
Row 0 → 1 dot
Row 1 → 2 dots
Row 2 → 3 dots
Row 3 → 4 dots
Row 4 → 5 dots
Plotting the dots:
plt.scatter(x, y, s=500, c='blue')
s=500 → Sets dot size.
c='blue' → Sets dot color to blue.
5. Adjusting Plot Limits
plt.xlim(-rows / 2, rows / 2)
plt.ylim(-rows, 1)
plt.xlim(-rows / 2, rows / 2) → Centers the triangle horizontally.
plt.ylim(-rows, 1) → Adjusts the vertical range to fit the triangle.
6. Formatting the Plot
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='datalim')
plt.title("Equilateral Triangle Pattern Plot", fontsize=14)
plt.axis('off') → Hides the axes for a cleaner look.
plt.gca().set_aspect('equal', adjustable='datalim') → Ensures that dot spacing remains uniform.
plt.title("Equilateral Triangle Pattern Plot", fontsize=14) → Adds a title.
7. Displaying the Final Output
plt.show()
Displays the equilateral triangle pattern.
0 Comments:
Post a Comment