{"spec_id":"dot-matrix-proportional","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\ndot-matrix-proportional: Dot Matrix Chart for Proportional Counts\nLibrary: plotnine 0.15.9 | Python 3.14.10\nQuality: 85/100 | Updated: 2026-11-18\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    coord_fixed,\n    element_rect,\n    element_text,\n    geom_point,\n    ggplot,\n    ggsave,\n    guide_legend,\n    guides,\n    labs,\n    scale_color_manual,\n    theme,\n    theme_void,\n)\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, one per category in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Constants\nREMAINDER = \"Other\"  # label for units that belong to no listed category\n\n# Columns: set these to your table's column names\nCATEGORY = \"Household solar status\"  # role: category\nCOUNT = \"Homes\"  # role: count\nTOTAL = \"Survey size\"  # 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: [\"Fully Solar-Powered\", \"Partially Solar-Powered\", \"No Solar Panels\"],\n        COUNT: [24, 41, 35],\n        TOTAL: [100, 100, 100],\n    }\n)\n\n# Plot: reads only df and the constants above\ntable = df.dropna(subset=[CATEGORY]).astype({CATEGORY: str})\nruns = table.groupby(CATEGORY, sort=False)[COUNT].sum().astype(float).fillna(0).astype(int)\ncategories = runs.index.tolist()\nlisted = len(categories)\ntotal = max(int(runs.sum()), int(df[TOTAL].astype(float).max(skipna=True) or 0))\nremainder = total - int(runs.sum())\nif remainder > 0:  # units that belong to no listed category stay in the grid as a neutral remainder\n    runs[REMAINDER] = remainder\n    categories.append(REMAINDER)\n\n# One dot per unit, filled left to right and top to bottom\ncols = int(np.ceil(np.sqrt(total)))\nlabels = np.repeat(categories, runs.to_numpy())\ngrid = pd.DataFrame(\n    {\n        \"col\": np.arange(total) % cols,\n        \"row\": -(np.arange(total) // cols),\n        CATEGORY: pd.Categorical(labels, categories=categories),\n    }\n)\nlegend_labels = [f\"{cat}  ({n})\" for cat, n in runs.items()]\ncolors = [IMPRINT_PALETTE[i] for i in range(listed)] + [INK_SOFT] * (len(categories) - listed)\ntitle = \"dot-matrix-proportional · python · plotnine · anyplot.ai\"\n\nplot = (\n    ggplot(grid, aes(x=\"col\", y=\"row\", color=CATEGORY))\n    + geom_point(size=10)\n    + scale_color_manual(values=colors, labels=legend_labels)\n    + guides(color=guide_legend(override_aes={\"size\": 8}))\n    + coord_fixed()\n    + labs(title=title, subtitle=f\"{CATEGORY} · n = {total} homes\", color=\"\")\n    + theme_void()\n    + theme(\n        figure_size=(8, 4.5),\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG),\n        plot_title=element_text(color=INK, size=15, ha=\"left\", weight=\"bold\"),\n        plot_subtitle=element_text(color=INK_SOFT, size=11, ha=\"left\"),\n        legend_background=element_rect(fill=ELEVATED_BG, color=INK_SOFT),\n        legend_text=element_text(color=INK_SOFT, size=9, margin={\"l\": 6, \"r\": 14}),\n        legend_key=element_rect(fill=ELEVATED_BG, color=\"None\"),\n        legend_position=\"right\",\n        plot_margin=0.03,\n    )\n)\n\n# Save\nggsave(plot, filename=f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\")\n"}