import matplotlib.pyplot as plt
import numpy as np
def draw_pentagon(ax,center,size):
angles=np.linspace(0,2*np.pi,6)[:-1]+np.pi/10
x=center[0]+size*np.cos(angles)
y=center[1]+size*np.sin(angles)
ax.plot(np.append(x,x[0]),np.append(y,y[0]),'b')
def draw_five_pentagons(size=1.0):
fig,ax=plt.subplots(figsize=(8,8))
positions=[(0,0),(1.5*size,0),(-1.5*size,0),(0.75*size,np.sqrt(3)*size),(-0.75*size,np.sqrt(3)*size)]
for pos in positions:
draw_pentagon(ax,pos,size)
ax.set_aspect('equal')
ax.axis('off')
plt.title('Pentagonal grid pattern plot')
plt.show()
draw_five_pentagons()
#source code --> clcoding.com
Code Explanation:
Imports
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot → Used for plotting the pentagons.
numpy → Used for numerical calculations, particularly for computing pentagon vertices.
Function: draw_pentagon
def draw_pentagon(ax, center, size):
"""Draws a pentagon given a center and size."""
Defines a function draw_pentagon that takes:
ax: Matplotlib axes where the pentagon will be drawn.
center: Coordinates (x, y) where the pentagon is placed.
size: The radius or size of the pentagon.
angles = np.linspace(0, 2 * np.pi, 6)[:-1] + np.pi / 10
np.linspace(0, 2 * np.pi, 6) → Generates 6 equally spaced angles from 0 to
2π (full circle).
[:-1] → Removes the last element to keep only 5 points (for a pentagon).
+ np.pi / 10 → Rotates the pentagon slightly for proper orientation.
x = center[0] + size * np.cos(angles)
y = center[1] + size * np.sin(angles)
Computes the x and y coordinates of the pentagon vertices using trigonometric functions:
np.cos(angles) → Calculates the x-coordinates.
np.sin(angles) → Calculates the y-coordinates.
ax.plot(np.append(x, x[0]), np.append(y, y[0]), 'b')
np.append(x, x[0]) → Ensures the first and last points are connected to close the pentagon.
ax.plot(..., 'b') → Plots the pentagon outline with a blue ('b') color.
Function: draw_five_pentagons
def draw_five_pentagons(size=1.0):
"""Draws exactly five pentagons."""
Defines a function to draw exactly five pentagons with a given size.
fig, ax = plt.subplots(figsize=(8, 8))
Creates a figure (fig) and axes (ax) with a size of 8×8 inches.
positions = [(0, 0), (1.5 * size, 0), (-1.5 * size, 0),
(0.75 * size, np.sqrt(3) * size), (-0.75 * size, np.sqrt(3) * size)]
Defines five fixed positions where pentagons will be placed:
(0, 0) → Center pentagon.
(±1.5 * size, 0) → Left and right pentagons.
(±0.75 * size, np.sqrt(3) * size) → Two pentagons above.
for pos in positions:
draw_pentagon(ax, pos, size)
Iterates through the positions list and calls draw_pentagon(ax, pos, size) to draw each pentagon.
ax.set_aspect('equal')
Ensures equal scaling so the pentagons do not appear distorted.
ax.axis('off')
Hides the x and y axes for a cleaner visual appearance.
plt.title("Pentagon grid pattern plot")
Sets a title for the plot.
plt.show()
Displays the final pentagon plot.
0 Comments:
Post a Comment