{"spec_id":"dot-matrix-proportional","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\ndot-matrix-proportional: Dot Matrix Chart for Proportional Counts\nLibrary: bokeh 3.10.2 | Python 3.14.10\nQuality: 83/100 | Updated: 2026-11-18\n\"\"\"\n\nimport os as _os\nimport sys\n\n\n# Prevent this file (bokeh.py) from shadowing the real bokeh package.\n# When Python runs a script, it inserts the script's directory into sys.path[0].\n# Since this file IS named bokeh.py, that directory entry must be removed first.\n_here = _os.path.dirname(_os.path.abspath(__file__))\nsys.path = [p for p in sys.path if _os.path.abspath(p) != _here]\ndel _here, _os\n\nimport math\nimport os\nimport time\nfrom pathlib import Path\n\nimport pandas as pd\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool, Legend, LegendItem\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme tokens\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\"\n\n# Imprint palette: all eight positions in canonical order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Columns: set these to your table's column names\nCATEGORY = \"Exercise frequency\"  # role: category\nCOUNT = \"Respondents\"  # role: count\nTOTAL = \"Population\"  # role: total\n\n# Data: replace this block with your own table, for example df = pd.read_csv(\"survey.csv\")\ndf = pd.DataFrame(\n    {\n        CATEGORY: [\"Daily\", \"3–5 times/week\", \"1–2 times/week\", \"Rarely / Never\"],\n        COUNT: [52, 74, 46, 28],\n        TOTAL: [200, 200, 200, 200],\n    }\n)\n\n# Plot: reads only df and the constants above\ndf = df.dropna(subset=[COUNT]).reset_index(drop=True)\ndf[COUNT] = df[COUNT].astype(int)\ntotal = max(int(df[TOTAL].max()), int(df[COUNT].sum()))\nn_cols = math.ceil(math.sqrt(2 * total))  # roughly 2:1 grid, 20 x 10 for 200\nn_rows = math.ceil(total / n_cols)\n\n# Fill left to right, top to bottom: dot k sits in column k % n_cols of row k // n_cols\ndots = df.loc[df.index.repeat(df[COUNT])].reset_index(drop=True)\ndots[\"x\"] = dots.index % n_cols\ndots[\"y\"] = n_rows - 1 - dots.index // n_cols\ndots[\"share\"] = (dots[COUNT] / total * 100).round().astype(int)\n\nW, H = 3200, 1800\ntitle = \"dot-matrix-proportional · python · bokeh · anyplot.ai\"\np = figure(\n    width=W,\n    height=H,\n    title=title,\n    toolbar_location=None,\n    x_range=(-0.8, n_cols - 0.2),\n    y_range=(-0.8, n_rows - 0.2),\n    match_aspect=True,\n    min_border_top=110,\n    min_border_bottom=60,\n    min_border_left=60,\n    min_border_right=60,\n)\n\nrenderers = []\nlegend_items = []\nfor i, cat in enumerate(df[CATEGORY]):\n    src = ColumnDataSource(dots[dots[CATEGORY] == cat])\n    r = p.scatter(\n        \"x\",\n        \"y\",\n        source=src,\n        color=IMPRINT_PALETTE[i % len(IMPRINT_PALETTE)],\n        size=104,\n        line_color=PAGE_BG,\n        line_width=2,\n    )\n    renderers.append(r)\n    count = int(df[COUNT].iloc[i])\n    share = round(count / total * 100)\n    legend_items.append(LegendItem(label=f\"{cat}  ({count} · {share}%)\", renderers=[r]))\n\np.add_tools(\n    HoverTool(\n        renderers=renderers, tooltips=[(\"Category\", f\"@{{{CATEGORY}}}\"), (COUNT, f\"@{{{COUNT}}}\"), (\"Share\", \"@share%\")]\n    )\n)\n\n# Theme-adaptive chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\np.title.align = \"center\"\np.xaxis.visible = False\np.yaxis.visible = False\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = None\n\n# Legend in a right panel, outside the dot grid\nlegend = Legend(\n    items=legend_items,\n    title=f\"{CATEGORY}  (n = {total})\",\n    title_text_font_size=\"34pt\",\n    title_text_color=INK,\n    background_fill_color=ELEVATED_BG,\n    border_line_color=INK_SOFT,\n    label_text_color=INK,\n    label_text_font_size=\"32pt\",\n    glyph_height=60,\n    glyph_width=60,\n    spacing=24,\n    padding=30,\n)\np.add_layout(legend, \"right\")\n\n# Save HTML, then screenshot it with headless Chrome\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\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)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ntime.sleep(3)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}