Sunday, 2 March 2025

Fractal tree pattern plot using python

 


import matplotlib.pyplot as plt

import numpy as np

def draw_branch(ax, x, y, length, angle, depth, branch_factor=0.7, angle_variation=30):

    if depth == 0:

        return

    new_x = x + length * np.cos(np.radians(angle))

    new_y = y + length * np.sin(np.radians(angle))

    ax.plot([x, new_x], [y, new_y], 'brown', lw=depth)

    draw_branch(ax, new_x, new_y, length * branch_factor, angle + angle_variation, depth - 1)

    draw_branch(ax, new_x, new_y, length * branch_factor, angle - angle_variation, depth - 1)

def fractal_tree():

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

    ax.set_xticks([])

    ax.set_yticks([])

    ax.set_frame_on(False)

    draw_branch(ax, 0, -1, 1, 90, depth=10)

    plt.xlim(-1, 1)

    plt.ylim(-1, 1.5)

    plt.title('Fractal tree pattern plot')

    plt.show()

fractal_tree()

#source code --> clcoding.com 


Code Explanation:

1. Importing Required Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot: Used to plot the fractal tree.

numpy: Used for mathematical operations like cos and sin (for angle calculations).


2. Recursive Function to Draw Branches

def draw_branch(ax, x, y, length, angle, depth, branch_factor=0.7, angle_variation=30):

This function draws branches recursively.

Parameters:

ax: The matplotlib axis for plotting.

(x, y): The starting coordinates of the branch.

length: The length of the current branch.

angle: The angle at which the branch grows.

depth: The recursion depth, representing how many branch levels to draw.

branch_factor: Determines how much shorter each successive branch is.

angle_variation: Determines how much the new branches deviate from the main branch.


3. Base Condition (Stopping Recursion)

if depth == 0:

    return

When depth == 0, recursion stops, meaning the smallest branches are reached.


4. Calculating the New Branch Endpoints

new_x = x + length * np.cos(np.radians(angle))

new_y = y + length * np.sin(np.radians(angle))

Uses trigonometry to compute the (x, y) coordinates of the new branch:

cos(angle): Determines the horizontal displacement.

sin(angle): Determines the vertical displacement.

np.radians(angle): Converts degrees to radians.


5. Drawing the Branch

ax.plot([x, new_x], [y, new_y], 'brown', lw=depth)

The branch is drawn as a brown line.

lw=depth: Line width decreases as depth decreases (thicker at the bottom, thinner at the tips).


6. Recursively Creating Two New Branches

draw_branch(ax, new_x, new_y, length * branch_factor, angle + angle_variation, depth - 1)

draw_branch(ax, new_x, new_y, length * branch_factor, angle - angle_variation, depth - 1)

Two smaller branches sprout from the current branch at:

angle + angle_variation (left branch).

angle - angle_variation (right branch).

Each new branch has:

A reduced length (length * branch_factor).

One less depth (depth - 1).


7. Creating the Fractal Tree

def fractal_tree():

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

    ax.set_xticks([])

    ax.set_yticks([])

    ax.set_frame_on(False)

Creates a figure and axis for plotting.

Removes ticks (set_xticks([]), set_yticks([])) and frame (set_frame_on(False)) for a clean look.


8. Calling the Recursive Function

draw_branch(ax, 0, -1, 1, 90, depth=10)

Starts drawing the tree at (0, -1), which is near the bottom center.

The initial branch:

Length = 1

Angle = 90° (straight up)

Depth = 10 (controls the number of branch levels).


9. Setting Plot Limits & Displaying the Tree

plt.xlim(-1, 1)

plt.ylim(-1, 1.5)

plt.title('Fractal tree pattern plot')

plt.show()

Limits the x-axis (-1 to 1) and y-axis (-1 to 1.5) to keep the tree centered.

Displays the fractal tree with plt.show().


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) 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 (76) 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)