Project 11: Fractal Tree Garden 🌳¶
Difficulty: 🟡 Intermediate
Run cells top to bottom. Each step builds on the previous one and saves real files under outputs/fractal_tree_garden/.
Description¶
Recursively draw fractal trees — a classic demo of recursion, trigonometry, and procedural generation.
Libraries & Modules¶
matplotlib.pyplotnumpy—cos,sin,radians- Built-in: recursion
Python Concepts You'll Practice¶
Recursion, base cases, trigonometry, procedural graphics
🎛️ Parameter Variations¶
DEPTH— 6 (fast) vs 12 (detailed, slower)ANGLE— branch spread in degrees (20 vs 45)RATIO— branch length shrink factor (0.65–0.8)COLOR— trunk/leaf color gradient
In [1]:
# Install dependencies for this project (safe to re-run)
import sys
!{sys.executable} -m pip install pillow numpy matplotlib wordcloud qrcode[pil] python-barcode fpdf2 jinja2 folium plotly pandas scipy ipywidgets -q
Skipping pip install (already installed)
In [2]:
# Interactive Jupyter setup — run this cell first
%matplotlib inline
from pathlib import Path
from IPython.display import display, Image as IPImage, HTML, Markdown, Audio, IFrame
OUTPUT_DIR = Path("outputs") / "fractal_tree_garden"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"✅ Outputs folder: {OUTPUT_DIR.resolve()}")
✅ Outputs folder: C:\Users\Hansel Yan\Projects\CodeItAll\outputs\fractal_tree_garden
Step 1 — Recursive tree drawer¶
In [3]:
import numpy as np
import matplotlib.pyplot as plt
# 🎛️ TWEAK THESE
DEPTH = 10
ANGLE = 25
RATIO = 0.72
TRUNK_LENGTH = 100
ORIGIN = (0, 0)
START_ANGLE = 90 # degrees up
def draw_branch(ax, x, y, length, angle_deg, depth):
if depth == 0 or length < 1:
return
rad = np.radians(angle_deg)
x2 = x + length * np.cos(rad)
y2 = y + length * np.sin(rad)
green = 0.2 + 0.6 * (depth / DEPTH)
ax.plot([x, x2], [y, y2], color=(0.4, green, 0.2), linewidth=depth * 0.4)
draw_branch(ax, x2, y2, length * RATIO, angle_deg + ANGLE, depth - 1)
draw_branch(ax, x2, y2, length * RATIO, angle_deg - ANGLE, depth - 1)
fig, ax = plt.subplots(figsize=(10, 8), facecolor="#1a1a2e")
ax.set_facecolor("#1a1a2e")
draw_branch(ax, ORIGIN[0], ORIGIN[1], TRUNK_LENGTH, START_ANGLE, DEPTH)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("Fractal Tree Garden — CodeItAll", color="white")
out = OUTPUT_DIR / "fractal_tree.png"
fig.savefig(out, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
plt.show()
print(f"Saved to {out}")
Saved to outputs\fractal_tree_garden\fractal_tree.png