{"spec_id":"waterfall-basic","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nwaterfall-basic: Basic Waterfall Chart\nLibrary: bokeh 3.9.2 | Python 3.13.14\nQuality: 90/100 | Updated: 2026-08-04\n\"\"\"\n\nimport os\nimport time\nfrom pathlib import Path\n\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, FactorRange, HoverTool, LabelSet, NumeralTickFormatter, Span\nfrom bokeh.plotting import figure\nfrom bokeh.transform import factor_cmap\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\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 — brand green for gains, the deferred semantic-red anchor\n# for losses, blue for the start/end totals\nPOSITIVE = \"#009E73\"\nNEGATIVE = \"#AE3030\"\nTOTAL = \"#4467A3\"\n\n# Data - quarterly financial breakdown from revenue to net income\ncategories = [\"Starting Revenue\", \"Product Sales\", \"Services\", \"Refunds\", \"Operating Costs\", \"Marketing\", \"Net Income\"]\nchanges = [150000, 50000, 35000, -8000, -75000, -22000, 0]\n\n# Waterfall bar positions\nrunning_total = 0\nbar_bottoms = []\nbar_tops = []\nbar_types = []\ndisplay_values = []\n\nfor i, change in enumerate(changes):\n    if i == 0:\n        # Starting total - full bar from 0\n        running_total = change\n        bar_bottoms.append(0)\n        bar_tops.append(running_total)\n        bar_types.append(\"Total\")\n        display_values.append(running_total)\n    elif i == len(categories) - 1:\n        # Final total - full bar from 0 to current running total\n        bar_bottoms.append(0)\n        bar_tops.append(running_total)\n        bar_types.append(\"Total\")\n        display_values.append(running_total)\n    else:\n        # Intermediate changes\n        if change >= 0:\n            bar_bottoms.append(running_total)\n            bar_tops.append(running_total + change)\n            bar_types.append(\"Increase\")\n        else:\n            bar_bottoms.append(running_total + change)\n            bar_tops.append(running_total)\n            bar_types.append(\"Decrease\")\n        running_total += change\n        display_values.append(change)\n\nmax_value = max(bar_tops)\nlabel_offset = max_value * 0.035\n\nlabel_texts = []\nfor i, val in enumerate(display_values):\n    if i == 0 or i == len(categories) - 1:\n        label_texts.append(f\"${val:,.0f}\")\n    elif val >= 0:\n        label_texts.append(f\"+${val:,.0f}\")\n    else:\n        label_texts.append(f\"-${abs(val):,.0f}\")\n\nsource = ColumnDataSource(\n    data={\n        \"categories\": categories,\n        \"bottom\": bar_bottoms,\n        \"top\": bar_tops,\n        \"type\": bar_types,\n        \"label\": label_texts,\n        \"label_y\": [top + label_offset for top in bar_tops],\n    }\n)\n\n# Running totals feed the connector segments between consecutive bars\nrunning_totals = []\nrt = 0\nfor i, change in enumerate(changes):\n    if i == 0:\n        rt = change\n    elif i < len(changes) - 1:\n        rt += change\n    running_totals.append(rt)\n\nconnector_xs = [[categories[i], categories[i + 1]] for i in range(len(categories) - 2)]\nconnector_ys = [[running_totals[i], running_totals[i]] for i in range(len(categories) - 2)]\n\n# Figure\np = figure(\n    x_range=FactorRange(*categories, range_padding=0.08),\n    width=3200,\n    height=1800,\n    title=\"waterfall-basic · python · bokeh · anyplot.ai\",\n    x_axis_label=\"Financial Category\",\n    y_axis_label=\"Amount ($)\",\n    toolbar_location=None,\n    min_border_bottom=160,\n    min_border_left=200,\n    min_border_top=110,\n    min_border_right=50,\n)\n\n# Bars colored by step type via a categorical color mapper — also drives\n# an automatic legend so Increase/Decrease/Total read without guesswork\nbars = p.vbar(\n    x=\"categories\",\n    top=\"top\",\n    bottom=\"bottom\",\n    width=0.62,\n    source=source,\n    fill_color=factor_cmap(\"type\", palette=[POSITIVE, NEGATIVE, TOTAL], factors=[\"Increase\", \"Decrease\", \"Total\"]),\n    line_color=PAGE_BG,\n    line_width=3,\n    legend_field=\"type\",\n)\n\np.add_tools(\n    HoverTool(renderers=[bars], tooltips=[(\"Category\", \"@categories\"), (\"Type\", \"@type\"), (\"Amount\", \"@label\")])\n)\n\n# Zero baseline for reference\np.add_layout(Span(location=0, dimension=\"width\", line_color=INK_SOFT, line_width=1.5, line_dash=\"dotted\"))\n\n# Dashed connectors linking each bar's cumulative edge to the next step\np.multi_line(xs=connector_xs, ys=connector_ys, line_color=INK_SOFT, line_width=2, line_dash=\"dashed\", line_alpha=0.55)\n\n# Value labels, batched from the shared source rather than looped Label() calls\np.add_layout(\n    LabelSet(\n        x=\"categories\",\n        y=\"label_y\",\n        text=\"label\",\n        source=source,\n        text_font_size=\"28pt\",\n        text_align=\"center\",\n        text_baseline=\"bottom\",\n        text_color=INK,\n    )\n)\n\n# Style\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\n\np.xaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_color = INK\n\np.xaxis.major_label_text_font_size = \"34pt\"\np.yaxis.major_label_text_font_size = \"34pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\np.xaxis.major_label_orientation = 0.3\np.yaxis.formatter = NumeralTickFormatter(format=\"$0,0\")\n\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\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = INK\np.ygrid.grid_line_alpha = 0.12\np.ygrid.grid_line_dash = [4, 4]\n\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None  # L-shaped frame — no closed rectangle border\n\np.legend.location = \"top_right\"\np.legend.orientation = \"vertical\"\np.legend.background_fill_color = ELEVATED_BG\np.legend.border_line_color = INK_SOFT\np.legend.label_text_color = INK_SOFT\np.legend.label_text_font_size = \"34pt\"\np.legend.glyph_height = 34\np.legend.glyph_width = 34\np.legend.spacing = 12\np.legend.padding = 14\np.legend.margin = 20\n\np.y_range.start = 0\np.y_range.end = max_value * 1.15\n\n# Save HTML\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome — Selenium 4 auto-resolves a working driver\nW, H = 3200, 1800\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)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\n# Headless Chrome's --window-size sets the OUTER window (phantom title-bar\n# reserved even headless), so pin the viewport exactly via CDP instead.\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ntime.sleep(3)  # let bokeh's JS render the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}