{"spec_id":"heatmap-clustered","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nheatmap-clustered: Clustered Heatmap\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 92/100 | Updated: 2026-05-09\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n\n# Fix import shadowing: import from site-packages first\n# Python automatically adds the script directory to sys.path[0], so we remove it\nif sys.path[0] in (\"\", \".\") or sys.path[0].endswith(\"/python\"):\n    sys.path.pop(0)\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.layouts import column\nfrom bokeh.layouts import row as bokeh_row\nfrom bokeh.models import (\n    BasicTicker,\n    ColorBar,\n    ColumnDataSource,\n    HoverTool,\n    Label,\n    LinearColorMapper,\n    PrintfTickFormatter,\n    Spacer,\n)\nfrom bokeh.plotting import figure\nfrom bokeh.resources import CDN\nfrom scipy.cluster.hierarchy import dendrogram, leaves_list, linkage\nfrom scipy.spatial.distance import pdist\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme colors\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\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# Data: Gene expression analysis (20 genes x 15 samples)\nnp.random.seed(42)\nn_genes = 20\nn_samples = 15\n\n# Gene names representing biological pathways\ngene_labels = [\n    \"CDK1\",\n    \"CCNB1\",\n    \"PLK1\",\n    \"AURKA\",\n    \"BUB1\",  # Cell cycle\n    \"GAPDH\",\n    \"LDHA\",\n    \"PKM\",\n    \"HK2\",\n    \"ENO1\",  # Metabolism\n    \"IL6\",\n    \"TNF\",\n    \"IFNG\",\n    \"IL1B\",\n    \"CXCL8\",  # Immune response\n    \"MYC\",\n    \"TP53\",\n    \"BRCA1\",\n    \"EGFR\",\n    \"VEGFA\",  # Cancer-related\n]\n\n# Sample names (tumor vs normal comparisons)\nsample_labels = [\n    \"T1_A\",\n    \"T1_B\",\n    \"T1_C\",\n    \"T2_A\",\n    \"T2_B\",  # Tumor group 1\n    \"T3_A\",\n    \"T3_B\",\n    \"T3_C\",  # Tumor group 2\n    \"N1_A\",\n    \"N1_B\",\n    \"N1_C\",\n    \"N2_A\",\n    \"N2_B\",\n    \"N2_C\",\n    \"N2_D\",  # Normal\n]\n\n# Generate expression data with cluster structure\ndata = np.random.randn(n_genes, n_samples) * 0.5\n\n# Cell cycle genes upregulated in tumors\ndata[0:5, 0:8] += 2.0\ndata[0:5, 8:15] -= 1.5\n\n# Metabolism genes moderately upregulated in tumors\ndata[5:10, 0:8] += 1.2\ndata[5:10, 8:15] -= 0.8\n\n# Immune genes show mixed pattern\ndata[10:15, 0:5] += 1.5\ndata[10:15, 5:8] -= 0.5\ndata[10:15, 8:12] += 0.8\ndata[10:15, 12:15] -= 1.2\n\n# Cancer-related genes upregulated in tumors\ndata[15:20, 0:8] += 1.8\ndata[15:20, 8:15] -= 1.0\n\n# Hierarchical clustering using Ward's method with Euclidean distance\nrow_linkage = linkage(pdist(data, metric=\"euclidean\"), method=\"ward\")\ncol_linkage = linkage(pdist(data.T, metric=\"euclidean\"), method=\"ward\")\n\n# Get leaf ordering\nrow_order = leaves_list(row_linkage)\ncol_order = leaves_list(col_linkage)\n\n# Reorder data and labels\ndata_ordered = data[row_order, :][:, col_order]\nrow_labels_ordered = [gene_labels[i] for i in row_order]\ncol_labels_ordered = [sample_labels[i] for i in col_order]\n\n# Build dendrograms manually to get coordinates\nrow_dendro = dendrogram(row_linkage, no_plot=True)\ncol_dendro = dendrogram(col_linkage, no_plot=True)\n\n# Layout dimensions - target 4800x2700 total\nheatmap_width = 4000\nheatmap_height = 1800\ndendro_size = 400\nlabel_space = 400\n\n# Color mapper - diverging colormap centered at 0\nmapper = LinearColorMapper(palette=\"RdBu11\", low=-3, high=3)\n\n# Prepare heatmap data using numerical coordinates\nx_data = []\ny_data = []\nvalue_data = []\ngene_name_data = []\nsample_name_data = []\nfor i in range(n_genes):\n    for j in range(n_samples):\n        x_data.append(j)\n        y_data.append(n_genes - 1 - i)  # Flip y so first row is at top\n        value_data.append(data_ordered[i, j])\n        gene_name_data.append(row_labels_ordered[i])\n        sample_name_data.append(col_labels_ordered[j])\n\nheatmap_source = ColumnDataSource(\n    data={\"x\": x_data, \"y\": y_data, \"value\": value_data, \"gene\": gene_name_data, \"sample\": sample_name_data}\n)\n\n# Create main heatmap figure with extra space for labels\nheatmap = figure(\n    width=heatmap_width + label_space,\n    height=heatmap_height + label_space,\n    x_range=(-0.5, n_samples + 5),  # Extra space for gene labels and axis label on right\n    y_range=(-5, n_genes - 0.5),  # Extra space for sample labels and axis label at bottom\n    toolbar_location=None,\n    tools=\"\",\n)\n\n# Render heatmap rectangles\nheatmap_rects = heatmap.rect(\n    x=\"x\",\n    y=\"y\",\n    width=1,\n    height=1,\n    source=heatmap_source,\n    fill_color={\"field\": \"value\", \"transform\": mapper},\n    line_color=\"white\",\n    line_width=0.5,\n)\n\n# Add hover tooltip\nhover = HoverTool(\n    renderers=[heatmap_rects], tooltips=[(\"Gene\", \"@gene\"), (\"Sample\", \"@sample\"), (\"Expression\", \"@value{0.00}\")]\n)\nheatmap.add_tools(hover)\n\n# Add column labels (samples) at bottom - angled for readability\nfor j, label in enumerate(col_labels_ordered):\n    heatmap.add_layout(\n        Label(\n            x=j,\n            y=-1.0,\n            text=label,\n            text_font_size=\"18pt\",\n            text_align=\"right\",\n            angle=0.785,  # 45 degrees\n            angle_units=\"rad\",\n            text_color=INK_SOFT,\n        )\n    )\n\n# Add row labels (genes) on right side\nfor i, label in enumerate(row_labels_ordered):\n    heatmap.add_layout(\n        Label(\n            x=n_samples + 0.2,\n            y=n_genes - 1 - i,\n            text=label,\n            text_font_size=\"18pt\",\n            text_align=\"left\",\n            text_baseline=\"middle\",\n            text_color=INK_SOFT,\n        )\n    )\n\n# Style heatmap\nheatmap.axis.visible = False\nheatmap.grid.grid_line_color = None\nheatmap.outline_line_color = None\nheatmap.background_fill_color = PAGE_BG\nheatmap.border_fill_color = PAGE_BG\n\n# Add axis labels as text (since axis is hidden)\nheatmap.add_layout(\n    Label(\n        x=(n_samples - 1) / 2,\n        y=-3.5,\n        text=\"Samples\",\n        text_font_size=\"22pt\",\n        text_align=\"center\",\n        text_baseline=\"top\",\n        text_font_style=\"bold\",\n        text_color=INK,\n    )\n)\nheatmap.add_layout(\n    Label(\n        x=n_samples + 3,\n        y=(n_genes - 1) / 2,\n        text=\"Genes\",\n        text_font_size=\"22pt\",\n        text_align=\"center\",\n        text_baseline=\"middle\",\n        angle=1.5708,  # 90 degrees in radians\n        angle_units=\"rad\",\n        text_font_style=\"bold\",\n        text_color=INK,\n    )\n)\n\n# Add color bar\ncolor_bar = ColorBar(\n    color_mapper=mapper,\n    ticker=BasicTicker(desired_num_ticks=7),\n    formatter=PrintfTickFormatter(format=\"%.1f\"),\n    label_standoff=20,\n    border_line_color=INK_SOFT,\n    location=(0, 0),\n    title=\"Expression (z-score)\",\n    title_text_font_size=\"18pt\",\n    title_text_color=INK,\n    major_label_text_font_size=\"16pt\",\n    major_label_text_color=INK_SOFT,\n    width=30,\n)\nheatmap.add_layout(color_bar, \"right\")\n\n# Create column dendrogram (top)\ncol_icoord = np.array(col_dendro[\"icoord\"])\ncol_dcoord = np.array(col_dendro[\"dcoord\"])\ncol_max_d = np.max(col_dcoord) * 1.1\n\ncol_dendro_fig = figure(\n    width=heatmap_width + label_space,\n    height=dendro_size,\n    x_range=heatmap.x_range,\n    y_range=(0, col_max_d),\n    toolbar_location=None,\n    tools=\"\",\n)\n\n# Draw column dendrogram lines\nfor i in range(len(col_icoord)):\n    # Scale x coordinates: dendrogram uses 5, 15, 25, ... for leaves\n    x_coords = [(x - 5) / 10 for x in col_icoord[i]]\n    col_dendro_fig.line(x_coords, col_dcoord[i], line_color=INK_SOFT, line_width=2)\n\ncol_dendro_fig.axis.visible = False\ncol_dendro_fig.grid.grid_line_color = None\ncol_dendro_fig.outline_line_color = None\ncol_dendro_fig.background_fill_color = PAGE_BG\ncol_dendro_fig.border_fill_color = PAGE_BG\n\n# Create row dendrogram (left)\nrow_icoord = np.array(row_dendro[\"icoord\"])\nrow_dcoord = np.array(row_dendro[\"dcoord\"])\nrow_max_d = np.max(row_dcoord) * 1.1\n\nrow_dendro_fig = figure(\n    width=dendro_size,\n    height=heatmap_height + label_space,\n    x_range=(row_max_d, 0),  # Reversed for left orientation\n    y_range=heatmap.y_range,\n    toolbar_location=None,\n    tools=\"\",\n)\n\n# Draw row dendrogram lines (rotated - swap x/y)\nfor i in range(len(row_icoord)):\n    # Scale y coordinates to match heatmap, flip to match y-axis direction\n    y_coords = [(y - 5) / 10 for y in row_icoord[i]]\n    row_dendro_fig.line(row_dcoord[i], y_coords, line_color=INK_SOFT, line_width=2)\n\nrow_dendro_fig.axis.visible = False\nrow_dendro_fig.grid.grid_line_color = None\nrow_dendro_fig.outline_line_color = None\nrow_dendro_fig.background_fill_color = PAGE_BG\nrow_dendro_fig.border_fill_color = PAGE_BG\n\n# Create title\ntitle_fig = figure(\n    width=heatmap_width + dendro_size + label_space,\n    height=100,\n    toolbar_location=None,\n    tools=\"\",\n    x_range=(0, 1),\n    y_range=(0, 1),\n)\ntitle_fig.text(\n    x=[0.5],\n    y=[0.5],\n    text=[\"heatmap-clustered · bokeh · pyplots.ai\"],\n    text_font_size=\"28pt\",\n    text_align=\"center\",\n    text_baseline=\"middle\",\n    text_color=INK,\n)\ntitle_fig.axis.visible = False\ntitle_fig.grid.grid_line_color = None\ntitle_fig.outline_line_color = None\ntitle_fig.background_fill_color = PAGE_BG\ntitle_fig.border_fill_color = PAGE_BG\n\n# Spacer for top-left corner\nspacer = Spacer(width=dendro_size, height=dendro_size)\n\n# Assemble layout\ntop_row = bokeh_row(spacer, col_dendro_fig)\nbottom_row = bokeh_row(row_dendro_fig, heatmap)\nlayout = column(title_fig, top_row, bottom_row)\n\n# Save outputs - HTML first\noutput_file(f\"plot-{THEME}.html\")\nsave(layout, resources=CDN, title=\"heatmap-clustered · bokeh · pyplots.ai\")\n\n# Screenshot with headless Chrome — Selenium 4 / Selenium Manager\nW, H = 4800, 2700\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)  # let bokeh's JS render the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}