{"spec_id":"dot-matrix-proportional","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\ndot-matrix-proportional: Dot Matrix Chart for Proportional Counts\nLibrary: seaborn 0.13.2 | Python 3.14.10\nQuality: 84/100 | Updated: 2026-11-18\n\"\"\"\n\nimport math\nimport os\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.lines import Line2D\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\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint palette: all eight positions, one per category in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\nsns.set_theme(\n    style=\"ticks\",\n    rc={\n        \"figure.facecolor\": PAGE_BG,\n        \"axes.facecolor\": PAGE_BG,\n        \"axes.edgecolor\": INK_SOFT,\n        \"axes.labelcolor\": INK,\n        \"text.color\": INK,\n        \"xtick.color\": INK_SOFT,\n        \"ytick.color\": INK_SOFT,\n        \"grid.color\": INK,\n        \"grid.alpha\": 0.10,\n        \"legend.facecolor\": ELEVATED_BG,\n        \"legend.edgecolor\": INK_SOFT,\n    },\n)\n\n# Columns: set these to your table's column names\nSOURCE = \"Energy source\"  # role: category\nCOUNT = \"Respondents\"  # role: count\nTOTAL = \"Total respondents\"  # role: total\n\n# Data: replace this block with your own table, one row per respondent, for example df = pd.read_csv(\"survey.csv\")\ndf = pd.DataFrame({SOURCE: [\"Solar Power\", \"Wind Energy\", \"Hydropower\", \"Other Sources\"], COUNT: [38, 29, 21, 12]})\ndf[TOTAL] = df[COUNT].sum()\n\n# Plot: reads only df and the constants above\ntable = df.dropna(subset=[COUNT])\ncounts = table.groupby(SOURCE, sort=False)[COUNT].sum().astype(int)\ncategories = list(counts.index)\ntotal = int(counts.sum())\n\n# Grid layout: as square as the total allows, filled left to right, top to bottom\ncols = math.ceil(math.sqrt(total))\nrows = math.ceil(total / cols)\ndots = (\n    pd.DataFrame({SOURCE: counts.index.repeat(counts.to_numpy())})\n    .reset_index(drop=True)\n    .assign(x=[i % cols for i in range(total)], y=[rows - 1 - i // cols for i in range(total)])\n)\n\nfig, ax = plt.subplots(figsize=(6, 6), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\nax.set_position([0.12, 0.27, 0.76, 0.62])\n\n# Dot size follows the grid: one dot fills ~78 % of its cell\ncell_pt = min(ax.get_position().width, ax.get_position().height) * fig.get_figwidth() * 72 / (max(cols, rows) + 0.6)\nsns.scatterplot(\n    data=dots,\n    x=\"x\",\n    y=\"y\",\n    hue=SOURCE,\n    hue_order=categories,\n    palette=IMPRINT_PALETTE[: len(categories)],\n    s=(0.78 * cell_pt) ** 2,\n    linewidth=0.8,\n    edgecolors=PAGE_BG,\n    ax=ax,\n    legend=False,\n)\nax.set_xlim(-0.8, cols - 0.2)\nax.set_ylim(-0.8, rows - 0.2)\nax.set_aspect(\"equal\")\n\n# Legend with counts and percentages, below the grid\nlegend_handles = [\n    Line2D(\n        [0],\n        [0],\n        marker=\"o\",\n        color=\"none\",\n        markerfacecolor=IMPRINT_PALETTE[i],\n        markeredgecolor=PAGE_BG,\n        markeredgewidth=0.5,\n        markersize=9,\n        label=f\"{name}  ·  {counts[name]} / {total}  ({counts[name] / total:.0%})\",\n    )\n    for i, name in enumerate(categories)\n]\nleg = ax.legend(\n    handles=legend_handles,\n    fontsize=9,\n    title=f\"{SOURCE}  (n = {total})\",\n    title_fontsize=10,\n    loc=\"upper center\",\n    bbox_to_anchor=(0.5, -0.04),\n    ncol=2,\n    frameon=True,\n    facecolor=ELEVATED_BG,\n    edgecolor=INK_SOFT,\n    handletextpad=0.8,\n    columnspacing=1.8,\n    borderpad=0.9,\n    labelspacing=0.8,\n)\nleg.get_title().set_color(INK)\nfor text in leg.get_texts():\n    text.set_color(INK_SOFT)\n\n# Style\ntitle = \"Energy Source Survey · dot-matrix-proportional · python · seaborn · anyplot.ai\"\nax.set_title(title, fontsize=round(12 * min(1, 67 / len(title))), fontweight=\"medium\", color=INK, pad=14)\nax.set_xlabel(\"\")\nax.set_ylabel(\"\")\nax.set_xticks([])\nax.set_yticks([])\nfor spine in ax.spines.values():\n    spine.set_visible(False)\n\nfig.text(0.5, 0.045, \"1 dot = 1 respondent\", ha=\"center\", va=\"center\", fontsize=9, color=INK_MUTED, style=\"italic\")\n\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}