{"spec_id":"dendrogram-radial","library":"letsplot","language":"python","code":"\"\"\" anyplot.ai\ndendrogram-radial: Radial Dendrogram\nLibrary: letsplot 4.11.0 | Python 3.14.10\nQuality: 75/100 | Updated: 2026-11-26\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom lets_plot import *\nfrom scipy.cluster.hierarchy import dendrogram, fcluster, linkage\nfrom sklearn.datasets import make_blobs\n\n\nLetsPlot.setup_html()\n\n# Theme tokens (see prompts/default-style-guide.md \"Background\" + \"Theme-adaptive Chrome\")\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint palette: all eight positions in canonical order, one per cluster\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Constants\nN_CLUSTERS = 4  # the tree is cut into this many clusters, colored as sectors\nSTRUCTURAL = \"Between clusters\"  # merges that join two different clusters\n\n# Columns: set these to your table's column names\nSAMPLE = \"Sample\"  # role: labels\n\n# Data: replace this block with your own table, for example\n# df = pd.read_csv(\"expression.csv\", index_col=SAMPLE); the linkage matrix and\n# the cluster assignment are derived from it below the block.\n# Synthetic marker-gene expression profiles for 32 tissue samples that form\n# 4 latent cell-type clusters\nnp.random.seed(42)\nexpression, _ = make_blobs(n_samples=32, centers=4, n_features=6, cluster_std=1.6, random_state=42)\ndf = pd.DataFrame(\n    expression,\n    columns=[f\"Gene {g}\" for g in \"ABCDEF\"],\n    index=pd.Index([f\"S{i + 1:02d}\" for i in range(32)], name=SAMPLE),\n)\n\n# Plot\nn_leaves = len(df)\nsample_labels = list(df.index)\nlinkage_matrix = linkage(df.to_numpy(), method=\"average\")\ncluster_ids = fcluster(linkage_matrix, t=N_CLUSTERS, criterion=\"maxclust\")\n\ncell_type_names = {cid: f\"Cell type {chr(64 + cid)}\" for cid in range(1, N_CLUSTERS + 1)}\ncluster_color = {cid: IMPRINT_PALETTE[cid - 1] for cid in cell_type_names}\n\n# Propagate cluster identity bottom-up through the linkage tree; a merge keeps\n# its children's cluster label only while both sides still share one cluster,\n# matching scipy's link_color_func node-id contract (node id = n_leaves + row)\nnode_cluster = {i: cluster_ids[i] for i in range(n_leaves)}\nfor i, (left, right, *_rest) in enumerate(linkage_matrix):\n    left_cluster = node_cluster[int(left)]\n    right_cluster = node_cluster[int(right)]\n    node_cluster[n_leaves + i] = left_cluster if left_cluster == right_cluster else None\n\nlink_labels = {}\nfor i in range(len(linkage_matrix)):\n    node_id = n_leaves + i\n    cluster = node_cluster[node_id]\n    link_labels[node_id] = cell_type_names[cluster] if cluster is not None else STRUCTURAL\n\nddata = dendrogram(\n    linkage_matrix, no_plot=True, labels=sample_labels, link_color_func=lambda node_id: link_labels[node_id]\n)\n\nleaf_order = ddata[\"leaves\"]  # original sample indices, left-to-right\nicoord = ddata[\"icoord\"]\ndcoord = ddata[\"dcoord\"]\nbranch_labels = ddata[\"color_list\"]\n\n# Column names of the derived drawing tables\nX, Y, PATH, CLUSTER = \"x\", \"y\", \"path_id\", \"cluster\"\nX_IN, Y_IN, X_OUT, Y_OUT = \"x_in\", \"y_in\", \"x_out\", \"y_out\"\nX_LABEL, Y_LABEL, ROTATION, HJUST = \"x_label\", \"y_label\", \"rotation\", \"hjust\"\nX0, X1, X_TEXT, TEXT, RING = \"x0\", \"x1\", \"x_text\", \"text\", \"ring_id\"\n\n# Radial layout — root at center, leaves on the circumference, radial\n# distance proportional to merge height (as in the linear dendrogram). The\n# center hole is sized to hold an in-panel legend (see \"Legend\" below) so the\n# figure never needs an external ggplot legend, which lets-plot's PNG\n# exporter fails to size correctly against a fixed square canvas.\nR_OUTER = 1.0\nR_INNER = 0.32\nmax_x = n_leaves * 10\nmax_height = linkage_matrix[:, 2].max()\n\n\ndef to_angle(x):\n    return (x / max_x) * 2 * np.pi\n\n\ndef to_radius(height):\n    return R_OUTER - (height / max_height) * (R_OUTER - R_INNER)\n\n\ndef polar_to_xy(angle, radius):\n    return radius * np.sin(angle), radius * np.cos(angle)\n\n\n# Branches — each scipy \"U\" shape (left riser, merge bar, right riser)\n# becomes a radial line, an arc sampled at the merge radius, and a radial\n# line back down, all pre-projected into Cartesian x/y\nbranch_rows = []\nfor path_id, ((xl, _x1, xr, _x3), (yl, ym, _y2, yr), branch_label) in enumerate(\n    zip(icoord, dcoord, branch_labels, strict=True)\n):\n    left_angle = to_angle(xl)\n    right_angle = to_angle(xr)\n    merge_radius = to_radius(ym)\n    left_child_radius = to_radius(yl)\n    right_child_radius = to_radius(yr)\n\n    arc_points = max(2, round(abs(right_angle - left_angle) / (2 * np.pi) * n_leaves * 8))\n    arc_angles = np.linspace(left_angle, right_angle, arc_points)\n\n    polar_points = [(left_angle, left_child_radius), (left_angle, merge_radius)]\n    polar_points += [(angle, merge_radius) for angle in arc_angles]\n    polar_points.append((right_angle, right_child_radius))\n\n    for order, (angle, radius) in enumerate(polar_points):\n        px, py = polar_to_xy(angle, radius)\n        branch_rows.append({PATH: path_id, \"order\": order, X: px, Y: py, CLUSTER: branch_label})\n\nbranches_df = pd.DataFrame(branch_rows)\n\n# Leaves — an outer ring tick (redundant cluster encoding) plus a rotated\n# label that stays upright and reads outward on both halves of the circle\nleaf_rows = []\nfor position, sample_index in enumerate(leaf_order):\n    angle = to_angle(5 + position * 10)\n    cluster = cell_type_names[cluster_ids[sample_index]]\n\n    x_in, y_in = polar_to_xy(angle, R_OUTER)\n    x_out, y_out = polar_to_xy(angle, R_OUTER + 0.035)\n    x_label, y_label = polar_to_xy(angle, R_OUTER + 0.075)\n\n    angle_deg = np.degrees(angle) % 360\n    if angle_deg < 180:\n        rotation = angle_deg - 90\n        hjust = 0\n    else:\n        rotation = angle_deg - 270\n        hjust = 1\n\n    leaf_rows.append(\n        {\n            SAMPLE: sample_labels[sample_index],\n            CLUSTER: cluster,\n            X_IN: x_in,\n            Y_IN: y_in,\n            X_OUT: x_out,\n            Y_OUT: y_out,\n            X_LABEL: x_label,\n            Y_LABEL: y_label,\n            ROTATION: rotation,\n            HJUST: hjust,\n        }\n    )\n\nleaves_df = pd.DataFrame(leaf_rows)\n\n# Radial reference guide — faint dashed rings at two intermediate merge-height\n# levels, so branch length has a scale anchor beyond eyeballing bare radius\nRING_FRACTIONS = [1 / 3, 2 / 3]\nring_angles = np.linspace(0, 2 * np.pi, 120)\nring_rows = []\nring_label_rows = []\nfor ring_id, fraction in enumerate(RING_FRACTIONS):\n    ring_height = fraction * max_height\n    ring_radius = to_radius(ring_height)\n    ring_rows += [{RING: ring_id, X: px, Y: py} for px, py in (polar_to_xy(a, ring_radius) for a in ring_angles)]\n    label_x, label_y = polar_to_xy(0.02, ring_radius)\n    ring_label_rows.append({X: label_x, Y: label_y, TEXT: f\"h={ring_height:.1f}\"})\n\nrings_df = pd.DataFrame(ring_rows)\nring_labels_df = pd.DataFrame(ring_label_rows)\n\n# Colors — Imprint palette for the 4 clusters, muted ink for merges that join\n# two different clusters (the conventional \"above cluster cut\" styling)\ncolor_values = {name: cluster_color[cid] for cid, name in cell_type_names.items()}\ncolor_values[STRUCTURAL] = INK_MUTED\n\n# Legend — drawn manually inside the empty center hole (color swatch + label\n# per row) instead of a ggplot guide_legend(). lets-plot's PNG exporter (via\n# ggsave scale=) cannot size a side/bottom legend against a fixed square\n# canvas without leaving the panel letterboxed by transparent padding, so an\n# in-panel legend is the reliable way to label 5 categories on this layout.\nLEGEND_STEP = 0.13\nlegend_entries = [(f\"Type {name[-1]}\", name) for name in cell_type_names.values()]\nlegend_entries.insert(len(legend_entries) // 2, (\"Mixed\", STRUCTURAL))\nlegend_df = pd.DataFrame(\n    [\n        {\n            Y: ((len(legend_entries) - 1) / 2 - i) * LEGEND_STEP,\n            X0: -0.22,\n            X1: -0.13,\n            X_TEXT: -0.10,\n            TEXT: text,\n            CLUSTER: cluster,\n        }\n        for i, (text, cluster) in enumerate(legend_entries)\n    ]\n)\n\n# Render\nVIEW = R_OUTER * 1.55  # half-width of the square view around the tree\ntitle = \"dendrogram-radial · python · letsplot · anyplot.ai\"\nplot = (\n    ggplot()\n    + geom_path(\n        aes(x=X, y=Y, group=RING),\n        data=rings_df,\n        color=INK_MUTED,\n        size=0.4,\n        alpha=0.5,\n        linetype=\"dashed\",\n        show_legend=False,\n    )\n    + geom_text(\n        aes(x=X, y=Y, label=TEXT),\n        data=ring_labels_df,\n        color=INK_MUTED,\n        size=3.5,\n        hjust=0,\n        vjust=-0.3,\n        show_legend=False,\n    )\n    + geom_path(aes(x=X, y=Y, group=PATH, color=CLUSTER), data=branches_df, size=1.1, show_legend=False)\n    + geom_segment(\n        aes(x=X_IN, y=Y_IN, xend=X_OUT, yend=Y_OUT, color=CLUSTER),\n        data=leaves_df,\n        size=3,\n        show_legend=False,\n        tooltips=layer_tooltips().line(f\"Sample|@{SAMPLE}\").line(f\"Cluster|@{CLUSTER}\"),\n    )\n    + geom_text(\n        aes(x=X_LABEL, y=Y_LABEL, label=SAMPLE, angle=ROTATION, hjust=HJUST),\n        data=leaves_df,\n        color=INK_SOFT,\n        size=8.5,\n        vjust=0.5,\n        show_legend=False,\n    )\n    + geom_segment(aes(x=X0, y=Y, xend=X1, yend=Y, color=CLUSTER), data=legend_df, size=3, show_legend=False)\n    + geom_text(\n        aes(x=X_TEXT, y=Y, label=TEXT), data=legend_df, color=INK_SOFT, size=6, hjust=0, vjust=0.5, show_legend=False\n    )\n    + scale_color_manual(values=color_values)\n    + coord_fixed(ratio=1, xlim=[-VIEW, VIEW], ylim=[-VIEW, VIEW])\n    + labs(title=title)\n    + theme(\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_grid=element_blank(),\n        panel_border=element_blank(),\n        axis_title=element_blank(),\n        axis_text=element_blank(),\n        axis_ticks=element_blank(),\n        axis_line=element_blank(),\n        plot_title=element_text(color=INK, size=16),\n    )\n)\n# A fixed aspect leaves the canvas edges transparent: the one-panel grid paints them\nplot = gggrid([plot]) + ggsize(600, 600) + theme(plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG))\n\n# Save\nggsave(plot, f\"plot-{THEME}.png\", path=\".\", scale=4)\nggsave(plot, f\"plot-{THEME}.html\", path=\".\")\n"}