Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                

Basic Icicle Chart in Bokeh (Python)

The same plot in 14 other libraries — Python: Altair, lets-plot, Matplotlib, Plotly, plotnine, Pygal, Seaborn; R: ggplot2; Julia: Makie.jl; JavaScript: Chart.js, D3.js, Apache ECharts, Highcharts, MUI X Charts. Compare all 15 side by side: Basic Icicle Chart in Python, R, Julia and JavaScript.

An icicle chart displaying hierarchical data as adjacent rectangles in a layered structure, where each rectangle's size represents its value in the hierarchy. Unlike treemaps that nest rectangles, icicle charts stack them in rows (horizontal) or columns (vertical), making parent-child relationships explicitly visible through spatial adjacency. This layout excels at showing both the hierarchy levels and the proportional values simultaneously.

Basic Icicle Chart rendered with Bokeh

Renders

Python source (Bokeh)

""" anyplot.ai
icicle-basic: Basic Icicle Chart
Library: bokeh 3.10.2 | Python 3.14.10
Quality: 87/100 | Updated: 2026-12-05
"""

import os
import time
from pathlib import Path

import pandas as pd
from bokeh.io import output_file, save
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


# Theme tokens
THEME = os.getenv("ANYPLOT_THEME", "light")
PAGE_BG = "#FAF8F1" if THEME == "light" else "#1A1A17"
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"

# Imprint palette: one position per hierarchy level
IMPRINT_PALETTE = ["#009E73", "#C475FD", "#4467A3", "#BD8233", "#AE3030", "#2ABCCD", "#954477", "#99B314"]

# Constants
W, H = 3200, 1800  # canonical landscape canvas
BORDER_LEFT, BORDER_RIGHT = 400, 50  # left border holds the level names
MAX_LABEL_PT = 34  # largest label size, the library prompt's tick-label size
MIN_LABEL_PT = 18  # a rectangle that needs less than this stays unlabeled
CHAR_PX_PER_PT = 0.73  # average glyph width in pixels per point of font size


def text_ink_on(fill):
    """Page-light or page-dark ink, whichever contrasts more with the hex fill."""
    channels = [int(fill[i : i + 2], 16) / 255 for i in (1, 3, 5)]
    lin = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels]
    lum = 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]
    # relative luminance of #1A1A17 is about 0.0097, of #FAF8F1 about 0.94
    return "#1A1A17" if (lum + 0.05) / 0.0597 > 0.99 / (lum + 0.05) else "#FAF8F1"


# Columns: set these to your table's column names
NAME = "Name"  # role: name
PARENT = "Parent"  # role: parent
VALUE = "Size (MB)"  # role: value

# Data: replace this block with your own table, for example df = pd.read_csv("tree.csv")
# File system with nested folders; only leaves carry a size, folders sum their children
df = pd.DataFrame(
    [
        ("Root", None, 0),
        ("Documents", "Root", 0),
        ("Media", "Root", 0),
        ("Code", "Root", 0),
        ("Reports", "Documents", 350),
        ("Contracts", "Documents", 250),
        ("Notes", "Documents", 150),
        ("Images", "Media", 500),
        ("Videos", "Media", 800),
        ("Audio", "Media", 300),
        ("Python", "Code", 400),
        ("JavaScript", "Code", 350),
        ("Data", "Code", 200),
    ],
    columns=[NAME, PARENT, VALUE],
)

# Plot: reads only df and the constants above
unit = VALUE[VALUE.find("(") + 1 : VALUE.rfind(")")] if "(" in VALUE else ""
kids = {name: [] for name in df[NAME]}
roots = []
for name, parent in zip(df[NAME], df[PARENT], strict=True):
    if pd.isna(parent) or parent not in kids:
        roots.append(name)
    else:
        kids[parent].append(name)

# Breadth-first order: every parent comes before its children
order = list(roots)
level = dict.fromkeys(roots, 0)
for name in order:
    for kid in kids[name]:
        level[kid] = level[name] + 1
        order.append(kid)

# Folder size is the sum of its children; leaves keep their own value
size = dict(zip(df[NAME], df[VALUE].fillna(0), strict=True))
for name in reversed(order):
    if kids[name]:
        size[name] = sum(size[kid] for kid in kids[name])

# Widths in 0..100 units, children split their parent's extent in proportion to size
total = sum(size[r] for r in roots)
left, width = {}, {}
cursor = 0.0
for r in roots:
    left[r], width[r] = cursor, 100 * size[r] / (total or 1)
    cursor += width[r]
for name in order:
    cursor = left[name]
    for kid in kids[name]:
        left[kid] = cursor
        width[kid] = width[name] * size[kid] / size[name] if size[name] else 0.0
        cursor += width[kid]

max_level = max(level.values())
px_per_unit = (W - BORDER_LEFT - BORDER_RIGHT) / 100

rows = []
for name in order:
    fill = IMPRINT_PALETTE[level[name]]
    value_text = f"{size[name]:g} {unit}".strip()
    label = f"{name}\n{value_text}"
    longest = max(len(str(name)), len(value_text))
    fit_pt = width[name] * px_per_unit * 0.78 / (CHAR_PX_PER_PT * longest)
    label_pt = min(MAX_LABEL_PT, fit_pt)
    rows.append(
        {
            "name": name,
            "x": left[name] + width[name] / 2,
            "y": max_level - level[name] + 0.5,
            "width": width[name],
            "fill": fill,
            "label": label if label_pt >= MIN_LABEL_PT else "",
            "label_size": f"{label_pt:.0f}pt",
            "label_color": text_ink_on(fill),
        }
    )
source = ColumnDataSource(pd.DataFrame(rows))

p = figure(
    width=W,
    height=H,
    title="icicle-basic · python · bokeh · anyplot.ai",
    y_axis_label="Hierarchy level",
    x_range=(0, 100),
    y_range=(0, max_level + 1),
    tools="",
    toolbar_location=None,
    min_border_left=BORDER_LEFT,
    min_border_right=BORDER_RIGHT,
    min_border_top=110,
    min_border_bottom=60,
)

# Opaque rectangles, one row per level; page-colored outlines act as thin borders
p.rect(
    x="x",
    y="y",
    width="width",
    height=1,
    source=source,
    fill_color="fill",
    fill_alpha=1,
    line_color=PAGE_BG,
    line_width=5,
)
p.text(
    x="x",
    y="y",
    text="label",
    source=source,
    text_align="center",
    text_baseline="middle",
    text_font_size="label_size",
    text_color="label_color",
    text_font_style="bold",
)

# Style
p.title.text_font_size = "50pt"
p.title.text_color = INK
p.title.align = "center"
p.background_fill_color = PAGE_BG
p.border_fill_color = PAGE_BG
p.outline_line_color = None

# Level names replace the value axis: position comes from the hierarchy, not from data
p.yaxis.ticker = [max_level - i + 0.5 for i in range(max_level + 1)]
p.yaxis.major_label_overrides = {max_level - i + 0.5: f"Level {i + 1}" for i in range(max_level + 1)}
p.yaxis.major_label_text_font_size = "34pt"
p.yaxis.major_label_text_color = INK_SOFT
p.yaxis.axis_label_text_font_size = "42pt"
p.yaxis.axis_label_text_color = INK
p.yaxis.major_tick_line_color = None
p.yaxis.minor_tick_line_color = None
p.yaxis.axis_line_color = None
p.xaxis.visible = False
p.xgrid.visible = False
p.ygrid.visible = False

# Save HTML
output_file(f"plot-{THEME}.html")
save(p)

# Screenshot with headless Chrome
opts = Options()
for arg in (
    "--headless=new",
    "--no-sandbox",
    "--disable-dev-shm-usage",
    "--disable-gpu",
    f"--window-size={W},{H}",
    "--hide-scrollbars",
):
    opts.add_argument(arg)
driver = webdriver.Chrome(options=opts)
driver.set_window_size(W, H)
driver.get(f"file://{Path(f'plot-{THEME}.html').resolve()}")
driver.execute_cdp_cmd(
    "Emulation.setDeviceMetricsOverride", {"width": W, "height": H, "deviceScaleFactor": 1, "mobile": False}
)
driver.execute_script(
    "document.documentElement.style.background = arguments[0]; document.body.style.background = arguments[0];", PAGE_BG
)
time.sleep(3)
driver.save_screenshot(f"plot-{THEME}.png")
driver.quit()

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/icicle-basic/bokeh/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.

{
  "spec_id": "icicle-basic",
  "language": "python",
  "library": "bokeh",
  "page": "https://anyplot.ai/icicle-basic/python/bokeh",
  "hub": "https://anyplot.ai/icicle-basic",
  "code_json": "https://api.anyplot.ai/specs/icicle-basic/bokeh/code",
  "spec_json": "https://api.anyplot.ai/specs/icicle-basic",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/icicle-basic/python/bokeh/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/icicle-basic/python/bokeh/plot-dark.png",
  "interactive_light_html": "https://storage.googleapis.com/anyplot-images/plots/icicle-basic/python/bokeh/plot-light.html",
  "interactive_dark_html": "https://storage.googleapis.com/anyplot-images/plots/icicle-basic/python/bokeh/plot-dark.html",
  "quality_score": 87.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Basic Icicle Chart on anyplot.ai.

Other implementations