{"spec_id":"bar-stacked-labeled","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nbar-stacked-labeled: Stacked Bar Chart with Total Labels\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 88/100 | Updated: 2026-05-18\n\"\"\"\n\nimport sys\n\n\n# Remove the script's directory from sys.path to avoid shadowing installed packages\nif sys.path and sys.path[0] and \"implementations\" in sys.path[0]:\n    sys.path.pop(0)\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Theme configuration\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# Okabe-Ito palette (positions 1-4)\nCOLORS = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\"]\n\n# Data - Quarterly revenue by product category (in millions $)\nnp.random.seed(42)\ncategories = [\"Q1\", \"Q2\", \"Q3\", \"Q4\"]\ncomponents = [\"Software\", \"Hardware\", \"Services\", \"Support\"]\n\n# Revenue data (realistic quarterly figures in millions)\ndata = {\n    \"Software\": [45, 52, 58, 62],\n    \"Hardware\": [30, 28, 35, 42],\n    \"Services\": [25, 32, 38, 45],\n    \"Support\": [15, 18, 22, 28],\n}\n\n# Create figure with theme-adaptive background\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Create stacked bars\nx = np.arange(len(categories))\nwidth = 0.6\nbottom = np.zeros(len(categories))\n\nbars_list = []\nfor i, (component, values) in enumerate(data.items()):\n    bars = ax.bar(x, values, width, bottom=bottom, label=component, color=COLORS[i], edgecolor=\"white\", linewidth=1.5)\n    bars_list.append(bars)\n    bottom += values\n\n# Calculate totals for labels\ntotals = np.sum([data[comp] for comp in components], axis=0)\n\n# Add total labels above each bar stack\nfor i, total in enumerate(totals):\n    ax.text(x[i], total + 3, f\"${total}M\", ha=\"center\", va=\"bottom\", fontsize=20, fontweight=\"bold\", color=INK)\n\n# Add segment labels inside bars for larger segments\nfor i, (_component, values) in enumerate(data.items()):\n    cumulative = np.zeros(len(categories))\n    for j in range(i):\n        cumulative += list(data.values())[j]\n    for j, val in enumerate(values):\n        if val >= 20:  # Only label segments >= 20\n            y_pos = cumulative[j] + val / 2\n            ax.text(x[j], y_pos, f\"{val}\", ha=\"center\", va=\"center\", fontsize=14, color=\"white\", fontweight=\"bold\")\n\n# Styling with theme-adaptive colors\nax.set_xlabel(\"Quarter\", fontsize=20, color=INK)\nax.set_ylabel(\"Revenue ($ Millions)\", fontsize=20, color=INK)\nax.set_title(\"bar-stacked-labeled · matplotlib · pyplots.ai\", fontsize=24, color=INK)\nax.set_xticks(x)\nax.set_xticklabels(categories)\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT, labelcolor=INK_SOFT)\n\n# Legend with theme-adaptive styling\nleg = ax.legend(fontsize=16, loc=\"upper left\", framealpha=0.9)\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    for text in leg.get_texts():\n        text.set_color(INK_SOFT)\n\nax.set_ylim(0, max(totals) * 1.15)  # Space for labels\n\n# Grid with theme-adaptive styling\nax.yaxis.grid(True, alpha=0.1, linestyle=\"-\", color=INK, linewidth=0.8)\n\n# Spines with theme-adaptive colors\nfor spine in (\"left\", \"bottom\"):\n    ax.spines[spine].set_color(INK_SOFT)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}