{"spec_id":"bar-stacked-percent","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nbar-stacked-percent: 100% Stacked Bar Chart\nLibrary: matplotlib 3.11.1 | Python 3.13.15\nQuality: 90/100 | Updated: 2026-08-18\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\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 (first series is ALWAYS position 1)\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\"]\n\n# Data: Energy mix by country (percentage of total electricity generation)\ncategories = [\"Germany\", \"France\", \"UK\", \"Spain\", \"Italy\", \"Poland\"]\ncomponents = [\"Renewables\", \"Nuclear\", \"Natural Gas\", \"Coal\", \"Other\"]\n\n# Raw values (TWh) - will be normalized to 100%\ndata = np.array(\n    [\n        [250, 70, 85, 110, 30],  # Germany\n        [120, 380, 45, 5, 25],  # France\n        [180, 55, 140, 15, 35],  # UK\n        [220, 60, 90, 10, 25],  # Spain\n        [130, 0, 180, 25, 40],  # Italy\n        [50, 0, 25, 200, 20],  # Poland\n    ]\n)\n\n# Normalize to percentages\npercentages = data / data.sum(axis=1, keepdims=True) * 100\n\n# Standout segment (largest single share) gets a subtle size emphasis\nstandout_row, standout_col = np.unravel_index(np.argmax(percentages), percentages.shape)\n\n# Plot\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Calculate cumulative percentages for stacking\nx = np.arange(len(categories))\nbar_width = 0.6\nbottom = np.zeros(len(categories))\n\n# Create stacked bars\nfor i, (component, color) in enumerate(zip(components, IMPRINT, strict=True)):\n    bars = ax.bar(\n        x, percentages[:, i], bar_width, bottom=bottom, label=component, color=color, edgecolor=PAGE_BG, linewidth=1.0\n    )\n\n    # In-segment percentage labels, suppressed below an 8% visibility threshold\n    labels = [f\"{pct:.0f}%\" if pct >= 8 else \"\" for pct in percentages[:, i]]\n    label_artists = ax.bar_label(bars, labels=labels, label_type=\"center\", fontsize=9, fontweight=\"bold\", color=INK)\n\n    # Emphasize the single largest segment in the whole chart (data storytelling focal point)\n    if i == standout_col:\n        label_artists[standout_row].set_fontsize(11)\n\n    bottom += percentages[:, i]\n\n# Style\nax.set_xlabel(\"Country\", fontsize=10, color=INK)\nax.set_ylabel(\"Percentage (%)\", fontsize=10, color=INK)\nax.set_title(\"bar-stacked-percent · python · matplotlib · anyplot.ai\", fontsize=12, color=INK, fontweight=\"medium\")\n\nax.set_xticks(x)\nax.set_xticklabels(categories, fontsize=8, color=INK_SOFT)\nax.tick_params(axis=\"y\", labelsize=8, colors=INK_SOFT)\n\nax.set_ylim(0, 100)\nax.set_yticks([0, 25, 50, 75, 100])\n\n# Legend\nleg = ax.legend(fontsize=8, loc=\"upper left\", bbox_to_anchor=(1.02, 1))\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    leg.get_frame().set_linewidth(0.8)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\n\n# Grid\nax.yaxis.grid(True, alpha=0.15, linewidth=0.8, color=INK)\nax.set_axisbelow(True)\n\n# Spines\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}