Thursday, 20 February 2025

Hexagonal pattern plot using python

 


import matplotlib.pyplot as plt

import numpy as np

import matplotlib.patches as patches


def draw_hexagonal_pattern(rows, cols, hex_size=1):

    fig, ax = plt.subplots(figsize=(6, 6))

    ax.set_xlim(-1, cols * 1.5)

    ax.set_ylim(-1, rows * np.sqrt(3))

    ax.set_aspect('equal')

    for row in range(rows):

        for col in range(cols):

            x = col * 1.5 * hex_size

            y = row * np.sqrt(3) * hex_size

            if col % 2 == 1:

                y += np.sqrt(3) / 2 * hex_size  

                hexagon = patches.RegularPolygon((x, y), numVertices=6, radius=hex_size, edgecolor='black', facecolor='lightblue')

            ax.add_patch(hexagon)

    plt.axis('off')  

    plt.show()

draw_hexagonal_pattern(6,6)

#source code --> clcoding.com 

Code Explanation:

Imports
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
matplotlib.pyplot: Used for plotting figures.
numpy: Provides mathematical functions (e.g., np.sqrt(3) for hexagonal height calculation).
matplotlib.patches: Contains shape objects like RegularPolygon, which we use to draw hexagons.

Function Definition
def draw_hexagonal_pattern(rows, cols, hex_size=1):
Defines a function draw_hexagonal_pattern that takes:
rows: Number of rows in the hexagonal pattern.
cols: Number of columns.
hex_size: The radius of each hexagon (default is 1).

Creating the Plot
    fig, ax = plt.subplots(figsize=(8, 8))
Creates a figure (fig) and axes (ax) to draw the pattern.
figsize=(8, 8): Sets the figure size to 8x8 inches.

    ax.set_xlim(-1, cols * 1.5)
    ax.set_ylim(-1, rows * np.sqrt(3))
    ax.set_aspect('equal')
ax.set_xlim(-1, cols * 1.5): Sets x-axis limits based on column count.
ax.set_ylim(-1, rows * np.sqrt(3)): Sets y-axis limits based on row count.
ax.set_aspect('equal'): Ensures hexagons retain their shape.

Loop to Create Hexagonal Grid
    for row in range(rows):
        for col in range(cols):
Loops through each row and column to place hexagons in a grid.

            x = col * 1.5 * hex_size
Calculates x-position: Each hexagon is spaced horizontally by 1.5 * hex_size.

            y = row * np.sqrt(3) * hex_size
Calculates y-position: Each hexagon is spaced vertically by √3 * hex_size.
            if col % 2 == 1:
                y += np.sqrt(3) / 2 * hex_size
Offsets every alternate column by √3/2 * hex_size to create a staggered effect.

Creating and Adding Hexagons
            hexagon = patches.RegularPolygon((x, y), numVertices=6, 
                                             radius=hex_size, edgecolor='black', 
                                             facecolor='lightblue')

Creates a hexagon using RegularPolygon:
(x, y): Center of the hexagon.
numVertices=6: Specifies it as a hexagon.
radius=hex_size: Defines the hexagon size.
edgecolor='black': Sets hexagon border color.
facecolor='lightblue': Sets fill color.

            ax.add_patch(hexagon)
Adds the hexagon to the plot (ax).
    plt.axis('off')  
    plt.show()
plt.axis('off'): Hides x and y axes.
plt.show(): Displays the figure.

Calling the Function
draw_hexagonal_pattern(6, 6)
Generates a hexagonal grid of 6 rows × 6 columns.


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (96) AI (38) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (188) C (77) C# (12) C++ (83) Course (67) Coursera (247) Cybersecurity (25) Data Analysis (1) Data Analytics (2) data management (11) Data Science (142) Data Strucures (8) Deep Learning (21) Django (16) Downloads (3) edx (2) Engineering (14) Euron (29) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (9) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (76) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1004) Python Coding Challenge (449) Python Quiz (86) Python Tips (4) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses

Python Coding for Kids ( Free Demo for Everyone)