{"spec_id":"dot-matrix-proportional","library":"altair","language":"python","code":"\"\"\" anyplot.ai\ndot-matrix-proportional: Dot Matrix Chart for Proportional Counts\nLibrary: altair 6.3.0 | Python 3.14.10\nQuality: 84/100 | Updated: 2026-11-19\n\"\"\"\n\nimport importlib\nimport math\nimport os\nimport sys\n\n\n# Remove the script's own directory from sys.path so \"import altair\" resolves\n# the library, not this file (which shares the library's name).\n_this_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if not (p and os.path.abspath(p) == _this_dir)]\n\nalt = importlib.import_module(\"altair\")\npd = importlib.import_module(\"pandas\")\nImage = importlib.import_module(\"PIL.Image\")\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\nNEUTRAL = \"#8C8B84\"  # remainder dots that belong to no listed category\n\n# Imprint palette: all eight positions, one per category in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Columns: set this to your table's column name\nRESPONSE = \"Response\"  # role: category\nCOUNT = \"Attendees\"  # role: count\nTOTAL = \"Total attendees\"  # role: total\n\n# Data: replace this block with your own table, one row per category in fill order,\n# for example df = pd.read_csv(\"survey.csv\")\n# Conference session survey: 100 attendees answering \"Would you recommend this talk?\"\ndf = pd.DataFrame({RESPONSE: [\"Agree\", \"Neutral\", \"Oppose\"], COUNT: [58, 27, 15]})\ndf[TOTAL] = df[COUNT].sum()\n\n# Plot: reads only df and the constants above\ncounts = pd.to_numeric(df[COUNT], errors=\"coerce\").fillna(0).astype(int)\nlisted = list(zip(df[RESPONSE].astype(str), counts, strict=True))\nlegend_label = {r: f\"{r} — {n}\" for r, n in listed}\n\n# One row per unit, filled left to right, top to bottom\nunits = [r for r, n in listed for _ in range(n)]\n# Units of the total that belong to no listed category stay in the grid as a neutral remainder\ntotal = max(int(pd.to_numeric(df[TOTAL], errors=\"coerce\").max()), len(units))\nif total > len(units):\n    legend_label[\"Other\"] = f\"Other — {total - len(units)}\"\n    units += [\"Other\"] * (total - len(units))\ngrid_cols = math.ceil(math.sqrt(total))\ndots = pd.DataFrame(\n    {\"unit\": units, \"col\": [i % grid_cols for i in range(total)], \"row\": [i // grid_cols for i in range(total)]}\n)\ndots[\"label\"] = dots[\"unit\"].map(legend_label)\n\ntitle = \"dot-matrix-proportional · python · altair · anyplot.ai\"\nratio = 67 / len(title) if len(title) > 67 else 1.0\n\nchart = (\n    alt.Chart(dots)\n    .mark_circle(size=1000, opacity=1.0)\n    .encode(\n        x=alt.X(\"col\", type=\"ordinal\", axis=None),\n        y=alt.Y(\"row\", type=\"ordinal\", axis=None, sort=\"ascending\"),\n        color=alt.Color(\n            \"label\",\n            type=\"nominal\",\n            title=RESPONSE,\n            sort=None,\n            scale=alt.Scale(\n                domain=list(legend_label.values()),\n                range=[NEUTRAL if k == \"Other\" else IMPRINT_PALETTE[i] for i, k in enumerate(legend_label)],\n            ),\n            legend=alt.Legend(\n                orient=\"bottom\",\n                direction=\"horizontal\",\n                titleFontSize=20,\n                labelFontSize=18,\n                symbolSize=500,\n                symbolType=\"circle\",\n                columnPadding=30,\n                columns=2,\n                titleLimit=300,\n                labelLimit=200,\n            ),\n        ),\n        tooltip=[alt.Tooltip(\"label\", type=\"nominal\", title=RESPONSE)],\n    )\n    .properties(\n        width=400,\n        height=400,\n        background=PAGE_BG,\n        title=alt.TitleParams(\n            text=title,\n            subtitle=\"Would you recommend this talk? 1 dot = 1 attendee\",\n            fontSize=round(22 * ratio),\n            subtitleFontSize=16,\n            color=INK,\n            subtitleColor=INK_SOFT,\n            anchor=\"start\",\n            offset=16,\n        ),\n    )\n    .configure_view(fill=PAGE_BG, stroke=None)\n    .configure_legend(\n        fillColor=ELEVATED_BG, strokeColor=INK_SOFT, labelColor=INK_SOFT, titleColor=INK, padding=12, cornerRadius=4\n    )\n    .configure_title(color=INK)\n)\n\nchart.save(f\"plot-{THEME}.png\", scale_factor=4.0)\nchart.save(f\"plot-{THEME}.html\")\n\n# Pad (never crop) to the canonical square canvas\nTARGET = 2400\nimg = Image.open(f\"plot-{THEME}.png\").convert(\"RGB\")\nif img.width > TARGET or img.height > TARGET:\n    raise SystemExit(f\"altair produced {img.width}x{img.height}, exceeds {TARGET}x{TARGET}; shrink width/height\")\ncanvas = Image.new(\"RGB\", (TARGET, TARGET), PAGE_BG)\ncanvas.paste(img, ((TARGET - img.width) // 2, (TARGET - img.height) // 2))\ncanvas.save(f\"plot-{THEME}.png\")\n"}