Sunday, 2 March 2025

Fern leaf pattern using python


 

import numpy as np

import matplotlib.pyplot as plt

def barnsley_fern(n):

    x=[0]

    y=[0]

    for _ in range(n):

        r=np.random.random()

        if r<0.01:

            x.append(0)

            y.append(0.16*y[-1])

        elif r<0.86:

            x.append(0.85*x[-1]+0.04*y[-1])

            y.append(-0.04*x[-2]+0.85*y[-1]+1.6)

        elif r<0.93:

            x.append(0.2*x[-1]-0.26*y[-1])

            y.append(0.23*x[-2]+0.22*y[-1]+1.6)

        else:

            x.append(-0.15*x[-1]+0.28*y[-1])

            y.append(0.26*x[-2]+0.24*y[-1]+0.44)

    return x,y

n=100000

x,y=barnsley_fern(n)

plt.figure(figsize=(6,10))

plt.scatter(x,y,s=0.2,color='green')

plt.axis('off')

plt.title('Fern leaf pattern')

plt.show()

#source code --> clcoding.com 


Code Explanation:

1. Importing Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is imported as np to handle numerical operations, such as generating random numbers.

matplotlib.pyplot is imported as plt to plot the fern.


2. Defining the Function barnsley_fern(n)

def barnsley_fern(n):

This function generates n points using Iterated Function Systems (IFS) to form the Barnsley Fern.


3. Initializing Lists to Store Coordinates

    x = [0]

    y = [0]

x and y are initialized as lists with the first point at (0,0).

These lists will store the x and y coordinates of the fern as points are generated.


4. Iterating n Times to Generate the Fern

    for _ in range(n):

The loop runs n times, generating n points.


5. Generating a Random Number for Transformation Selection

        r = np.random.random()

A random number r between 0 and 1 is generated.

This number determines which transformation (out of 4) will be applied to the current point.


6. Applying One of the Four Transformations

        if r < 0.01:

            x.append(0)

            y.append(0.16 * y[-1])

Transformation 1 (Stem) – Probability 1%

Maps all points to the stem of the fern.

Keeps x = 0, and y is scaled down (0.16*y[-1]).

        elif r < 0.86:

            x.append(0.85 * x[-1] + 0.04 * y[-1])

            y.append(-0.04 * x[-2] + 0.85 * y[-1] + 1.6)

Transformation 2 (Main Leaf) – Probability 85%

Forms the largest part of the fern.

The new (x, y) point is calculated using a linear transformation.

        elif r < 0.93:

            x.append(0.2 * x[-1] - 0.26 * y[-1])

            y.append(0.23 * x[-2] + 0.22 * y[-1] + 1.6)

Transformation 3 (Left Leaflets) – Probability 7%

Creates the left leaflets of the fern.



Uses different coefficients in the affine transformation.

        else:

            x.append(-0.15 * x[-1] + 0.28 * y[-1])

            y.append(0.26 * x[-2] + 0.24 * y[-1] + 0.44)

Transformation 4 (Right Leaflets) – Probability 7%

Forms the right leaflets of the fern.


7. Returning the Generated Points

    return x, y

The function returns the lists x and y, which contain all generated points.


8. Calling the Function to Generate 100,000 Points

n = 100000  

x, y = barnsley_fern(n)

Calls barnsley_fern(n) with n = 100000 to generate 100,000 points.

The returned values x and y contain the coordinates of the fern.


9. Plotting the Fern

plt.figure(figsize=(6, 10))

Creates a figure with a 6x10 inches size.


plt.scatter(x, y, s=0.2, color='green')

scatter() plots the points from x and y.

s=0.2 makes the points very small for a finer look.

color='green' colors the fern green.


10. Removing Axes and Displaying the Plot

plt.axis('off')

Hides the axes for a cleaner look.


plt.title("Fern Leaf Pattern")

Adds a title to the plot.

plt.show()

Displays the Barnsley Fern.


Honeycomb pattern plot using python

 



import matplotlib.pyplot as plt

import numpy as np

x=np.random.randn(10000)

y=np.random.randn(10000)

plt.hexbin(x,y,gridsize=30,cmap='Blues',edgecolor='gray')

plt.colorbar(label='Count in bin')

plt.title('Honeycomb pattern plot')

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()

 #source code --> clcoding.com 


Code Explanation:

1. Import Required Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot is used for plotting.

numpy is used for numerical operations like generating random data.


2. Generate Random Data

x = np.random.randn(10000)

y = np.random.randn(10000)

np.random.randn(10000) generates 10,000 random numbers from a normal distribution (mean = 0, standard deviation = 1).

Two sets of such numbers are stored in x and y, forming random (x, y) pairs.


3. Create a Hexbin Plot

plt.hexbin(x, y, gridsize=30, cmap='Blues', edgecolor='gray')

hexbin(x, y, gridsize=30, cmap='Blues', edgecolor='gray'):

gridsize=30: Specifies the number of hexagonal bins in the grid (higher value = smaller hexagons).

cmap='Blues': Uses the "Blues" colormap for coloring the hexagons based on data density.

edgecolor='gray': Adds gray borders around hexagons for better visibility.


4. Add a Color Bar

plt.colorbar(label='Count in bin')

plt.colorbar() adds a color scale bar.

label='Count in bin' describes the color bar as representing the number of points inside each hexagon.


5. Customize the Plot

plt.title('Honeycomb pattern plot')

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

Adds title and axis labels.


6. Display the Plot

plt.show()

Renders the plot.



Lattice pattern plot using python


 import matplotlib.pyplot as plt

import numpy as np


x,y=np.meshgrid(np.arange(0,10,1),np.arange(0,10,1))

x=x.flatten()

y=y.flatten()


plt.figure(figsize=(6,6))

plt.scatter(x,y,s=100,c='blue',edgecolor='black')

plt.axis('equal')

plt.grid(True,linestyle='--',alpha=0.5)

plt.title('Lattice pattern plot')

plt.show()

 #source code --> clcoding.com 


Code Explanation:

1. Import Necessary Libraries

import matplotlib.pyplot as plt

import numpy as np

Matplotlib is used for visualization.

NumPy is used for numerical computations.


2. Create a Grid of Points

x, y = np.meshgrid(np.arange(0, 10, 1), np.arange(0, 10, 1))

np.arange(0, 10, 1) generates values from 0 to 9 (step = 1).

np.meshgrid() creates a 2D grid from these values:

x contains column values (repeats horizontally).

y contains row values (repeats vertically).

Example Output of np.meshgrid()

If np.arange(0, 3, 1) is used instead of 0 to 10, it would generate:

x =

[[0 1 2]

 [0 1 2]

 [0 1 2]]


y =

[[0 0 0]

 [1 1 1]

 [2 2 2]]

This represents a grid of points at (0,0), (1,0), (2,0), (0,1), (1,1), (2,1), etc.


3. Flatten the Grid into 1D Arrays

x = x.flatten()

y = y.flatten()

.flatten() converts the 2D grid into 1D arrays of x and y coordinates.

Now, we have all grid points in a simple list format for plotting.


4. Create the Scatter Plot

plt.figure(figsize=(6,6))

figsize=(6,6) ensures a square figure to maintain equal spacing.

plt.scatter(x, y, s=100, c='blue', edgecolor='black')

plt.scatter(x, y, s=100, c='blue', edgecolor='black')

Plots blue dots (c='blue').

Each dot has a size of 100 (s=100).

A black border (edgecolor='black') surrounds each dot.

5. Adjust the Plot Formatting

plt.axis('equal')

Ensures both x and y axes have the same scale, preventing distortion.

plt.grid(True, linestyle='--', alpha=0.5)

Enables grid lines (plt.grid(True)) for better visualization.

Dashed grid lines (linestyle='--').

alpha=0.5 makes the grid lines slightly transparent.

plt.title('Lattice pattern plot')

Sets the title of the plot.


6. Display the Plot

plt.show()

Displays the final lattice pattern.


Octagonal grid pattern plot Using Python



 import matplotlib.pyplot as plt

import numpy as np


def draw_octagon(ax, center, size):

    """Draws an octagon given a center and size."""

    angles = np.linspace(0, 2 * np.pi, 9)[:-1] + np.pi / 8

    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_octagonal_grid(rows, cols, size=1.0):

    """Generates a grid of octagons."""

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

    dx = 2 * size * np.cos(np.pi / 8)

    dy = 2 * size * np.sin(np.pi / 8) + size

    

    for row in range(rows):

        for col in range(cols):

            x_offset = col * dx

            y_offset = row * dy - (col % 2) * (dy / 2)

            draw_octagon(ax, (x_offset, y_offset), size)

    

    ax.set_aspect('equal')

    ax.axis('off')

    plt.title('octagonal pattern plot')

    plt.show()


rows, cols = 5, 5  

draw_octagonal_grid(rows, cols)

#source code --> clcoding.com 


Code Explanation:

1. Import Required Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot → Used for plotting the octagons.

numpy → Used for numerical calculations (especially trigonometric functions for octagon vertices).


2. Function to Draw a Single Octagon

def draw_octagon(ax, center, size):

    """Draws an octagon given a center and size."""

This function draws a single octagon at the specified center with a given size.


    angles = np.linspace(0, 2 * np.pi, 9)[:-1] + np.pi / 8

np.linspace(0, 2 * np.pi, 9) → Generates 9 angles from 0 to 

2π (full circle).

[:-1] → Removes the last element, keeping 8 points (for an octagon).

+ np.pi / 8 → Rotates the octagon 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 octagon vertices using trigonometric functions:

np.cos(angles) → Calculates x-coordinates.

np.sin(angles) → Calculates y-coordinates.


    ax.plot(np.append(x, x[0]), np.append(y, y[0]), 'b')

np.append(x, x[0]) → Connects the first and last points to close the octagon.

ax.plot(..., 'b') → Plots the octagon outline using a blue ('b') color.


3. Function to Draw an Octagonal Grid

def draw_octagonal_grid(rows, cols, size=1.0):

    """Generates a grid of octagons."""

Defines a function to generate a grid of octagons with given rows, columns, and octagon size.


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

Creates a figure (fig) and axes (ax) with a size of 8×8 inches.


    dx = 2 * size * np.cos(np.pi / 8)

    dy = 2 * size * np.sin(np.pi / 8) + size

dx (horizontal spacing) → Uses cosine to calculate the horizontal distance between octagons.

dy (vertical spacing) → Uses sine and size to set the vertical gap between rows.


    for row in range(rows):

        for col in range(cols):

Loops through the grid with rows × cols iterations to draw multiple octagons.


            x_offset = col * dx

            y_offset = row * dy - (col % 2) * (dy / 2)

x_offset = col * dx → Determines the x-coordinate for each octagon.

y_offset = row * dy - (col % 2) * (dy / 2) →

Adjusts vertical alignment so alternate columns are slightly shifted downwards, creating a staggered pattern.


            draw_octagon(ax, (x_offset, y_offset), size)

Calls draw_octagon() to draw an octagon at each calculated position.


    ax.set_aspect('equal')

Ensures equal scaling so the octagons do not appear distorted.


    ax.axis('off')

Hides the x and y axes for a clean visual representation.


    plt.title('octagonal pattern plot')

Sets the plot title.

    plt.show()

Displays the final grid of octagons.


4. Function Call

rows, cols = 5, 5  

draw_octagonal_grid(rows, cols)


Concentric circle plot using python




import numpy as np
import matplotlib.pyplot as plt

fig,ax=plt.subplots(figsize=(6,6))
num_circles=10
radii=np.linspace(0.2,2,num_circles)
for r in radii:
    circle=plt.Circle((0,0),r,color='b',fill=False,linewidth=2)
    ax.add_patch(circle)

ax.set_xlim(-2.5,2.5)
ax.set_ylim(-2.5,2.5)
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title("Concentric circle plot")
plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot: The core library for creating visualizations.

numpy: Used to generate evenly spaced values for the circle radii.


2. Create the Figure and Axis

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

fig, ax = plt.subplots() creates a figure (fig) and an axis (ax), which we use to draw our circles.

figsize=(6,6) ensures the figure is a square, keeping the circles proportionate.


3. Define the Circles

num_circles = 10  # Number of concentric circles

radii = np.linspace(0.2, 2, num_circles)  # Generate 10 radius values between 0.2 and 2

num_circles = 10: We want 10 circles.

np.linspace(0.2, 2, num_circles):

Generates 10 values between 0.2 (smallest circle) and 2 (largest circle).

These values represent the radii of the circles.


4. Draw Each Circle

for r in radii:

    circle = plt.Circle((0, 0), r, color='b', fill=False, linewidth=2)  # Blue hollow circles

    ax.add_patch(circle)

We loop through each radius in radii:

plt.Circle((0, 0), r, color='b', fill=False, linewidth=2):

(0,0): Sets the center at the origin.

r: Defines the radius of the circle.

color='b': Blue (b) outline color.

fill=False: Ensures only the outline is drawn, not a solid circle.

linewidth=2: Sets the thickness of the circle outline.

ax.add_patch(circle): Adds the circle to the plot.


5. Adjust the Plot

ax.set_xlim(-2.5, 2.5)

ax.set_ylim(-2.5, 2.5)

ax.set_aspect('equal')  # Ensures circles are perfectly round

ax.set_xlim(-2.5, 2.5) / ax.set_ylim(-2.5, 2.5):

Expands the plot’s limits slightly beyond the largest circle (radius 2).

ax.set_aspect('equal'):

Prevents distortion by ensuring equal scaling on both axes.


6. Hide Axes for a Clean Look

ax.set_xticks([])

ax.set_yticks([])

ax.spines['top'].set_visible(False)

ax.spines['right'].set_visible(False)

ax.spines['left'].set_visible(False)

ax.spines['bottom'].set_visible(False)

ax.set_xticks([]) / ax.set_yticks([]): Removes tick marks from the plot.

ax.spines[...]: Hides the border lines around the plot.


7. Display the Plot

plt.show()

plt.show() renders and displays the plot.


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 (189) 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) Events (6) 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 (78) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1012) Python Coding Challenge (452) Python Quiz (91) Python Tips (5) 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)