{"spec_id":"bar-stacked-labeled","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nbar-stacked-labeled: Stacked Bar Chart with Total Labels\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 90/100 | Updated: 2026-05-18\n\"\"\"\n\nimport os\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool, LabelSet\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme tokens (see prompts/default-style-guide.md)\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# Okabe-Ito palette\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\"]\n\n# Data - Quarterly revenue by product category\nnp.random.seed(42)\ncategories = [\"Q1\", \"Q2\", \"Q3\", \"Q4\"]\ncomponents = [\"Electronics\", \"Clothing\", \"Home & Garden\", \"Sports\"]\n\ndata = {\n    \"Electronics\": [45, 52, 48, 68],\n    \"Clothing\": [32, 38, 55, 72],\n    \"Home & Garden\": [28, 42, 38, 35],\n    \"Sports\": [18, 25, 32, 45],\n}\n\n# Calculate totals for labels\ntotals = [sum(data[comp][i] for comp in components) for i in range(len(categories))]\n\n# Create figure with categorical x-axis\np = figure(\n    x_range=categories,\n    width=4800,\n    height=2700,\n    title=\"bar-stacked-labeled · Python · bokeh · anyplot.ai\",\n    x_axis_label=\"Quarter\",\n    y_axis_label=\"Revenue ($M)\",\n    toolbar_location=\"right\",\n)\n\n# Track bottom positions for stacking\nbottoms = [0] * len(categories)\n\n# Plot stacked bars\nfor _comp_idx, (comp, color) in enumerate(zip(components, IMPRINT, strict=True)):\n    tops = [b + v for b, v in zip(bottoms, data[comp], strict=True)]\n    source = ColumnDataSource(\n        data={\n            \"categories\": categories,\n            \"values\": data[comp],\n            \"bottoms\": bottoms.copy(),\n            \"tops\": tops,\n            \"component\": [comp] * len(categories),\n        }\n    )\n\n    bars = p.vbar(\n        x=\"categories\",\n        top=\"tops\",\n        bottom=\"bottoms\",\n        width=0.7,\n        source=source,\n        color=color,\n        legend_label=comp,\n        line_color=\"white\",\n        line_width=2,\n    )\n\n    # Add hover tool to show detailed segment information\n    hover = HoverTool(\n        renderers=[bars], tooltips=[(\"Quarter\", \"@categories\"), (\"Category\", \"@component\"), (\"Value\", \"@values M\")]\n    )\n    p.add_tools(hover)\n\n    # Update bottoms for next stack\n    bottoms = tops.copy()\n\n# Add total labels above each bar stack\nlabel_source = ColumnDataSource(\n    data={\n        \"x\": categories,\n        \"y\": [t + 5 for t in totals],  # Offset above bars\n        \"text\": [f\"${t}M\" for t in totals],\n    }\n)\n\nlabels = LabelSet(\n    x=\"x\",\n    y=\"y\",\n    text=\"text\",\n    source=label_source,\n    text_font_size=\"36pt\",\n    text_font_style=\"bold\",\n    text_color=INK,\n    text_align=\"center\",\n    text_baseline=\"bottom\",\n)\np.add_layout(labels)\n\n# Styling for large canvas (4800x2700)\np.title.text_font_size = \"28pt\"\np.title.text_color = INK\np.xaxis.axis_label_text_font_size = \"22pt\"\np.yaxis.axis_label_text_font_size = \"22pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\np.xaxis.major_label_text_font_size = \"18pt\"\np.yaxis.major_label_text_font_size = \"18pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\n\n# Axis line styling\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\n\n# Grid styling\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = INK\np.ygrid.grid_line_alpha = 0.10\n\n# Legend styling - position in bottom left to avoid crowding labels\np.legend.location = \"bottom_left\"\np.legend.label_text_font_size = \"18pt\"\np.legend.label_text_color = INK_SOFT\np.legend.glyph_height = 35\np.legend.glyph_width = 35\np.legend.spacing = 12\np.legend.padding = 20\np.legend.background_fill_color = ELEVATED_BG\np.legend.background_fill_alpha = 0.95\np.legend.border_line_color = INK_SOFT\n\n# Background colors (theme-adaptive)\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = INK_SOFT\n\n# Set y-axis range to accommodate labels\np.y_range.end = max(totals) + 30\n\n# Save HTML (required for interactive library)\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome (Selenium)\nW, H = 4800, 2700\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)  # let bokeh's JS render the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}