{"spec_id":"slope-basic","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nslope-basic: Basic Slope Chart (Slopegraph)\nLibrary: bokeh 3.9.2 | Python 3.13.14\nQuality: 92/100 | Updated: 2026-07-25\n\"\"\"\n\nimport os\nimport time\nfrom pathlib import Path\n\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool, Label\nfrom bokeh.plotting import figure\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# Direction colors follow the semantic exception (up/gain -> green, down/loss -> red)\nINCREASE_COLOR = \"#009E73\"  # Imprint position 1 (brand green)\nDECREASE_COLOR = \"#AE3030\"  # Imprint position 5 (matte red, semantic anchor)\n\n# Endpoint-label TEXT uses theme-tuned variants of the direction colors so the\n# small text clears WCAG contrast against its background; the lines, markers,\n# and legend swatches stay at the true Imprint colors above for palette identity.\nLABEL_INCREASE_COLOR = \"#006644\" if THEME == \"light\" else INCREASE_COLOR  # deeper green: 6.6:1 on light bg\nLABEL_DECREASE_COLOR = \"#E86A6A\" if THEME == \"dark\" else DECREASE_COLOR  # lighter red: 5.6:1 on dark bg\n\nproducts = [\n    \"Wireless Earbuds\",\n    \"Smart Thermostat\",\n    \"Espresso Machine\",\n    \"Standing Desk\",\n    \"Air Purifier\",\n    \"Bluetooth Speaker\",\n    \"Robot Vacuum\",\n    \"Desk Lamp\",\n    \"Water Bottle\",\n    \"Backpack\",\n]\nq1_sales = [85, 72, 91, 45, 68, 53, 78, 62, 40, 88]\nq4_sales = [92, 65, 88, 71, 74, 48, 95, 58, 67, 82]\n\ncolors = [INCREASE_COLOR if end > start else DECREASE_COLOR for start, end in zip(q1_sales, q4_sales, strict=True)]\nlabel_colors = [\n    LABEL_INCREASE_COLOR if end > start else LABEL_DECREASE_COLOR for start, end in zip(q1_sales, q4_sales, strict=True)\n]\ndirections = [\"Increase\" if end > start else \"Decrease\" for start, end in zip(q1_sales, q4_sales, strict=True)]\n\n# Spread label y-positions apart so dense clusters don't overlap (inlined per\n# side, no helper function, per KISS structure — imports -> data -> plot -> save)\nlabel_ys = {}\nfor side, ys in ((\"left\", q1_sales), (\"right\", q4_sales)):\n    order = sorted(range(len(ys)), key=lambda i: ys[i])\n    adjusted = [float(ys[i]) for i in order]\n    for _ in range(30):\n        changed = False\n        for i in range(1, len(adjusted)):\n            if adjusted[i] - adjusted[i - 1] < 4.5:\n                mid = (adjusted[i] + adjusted[i - 1]) / 2\n                adjusted[i - 1] = mid - 2.25\n                adjusted[i] = mid + 2.25\n                changed = True\n        if not changed:\n            break\n    spread = [0.0] * len(ys)\n    for new_i, orig_i in enumerate(order):\n        spread[orig_i] = adjusted[new_i]\n    label_ys[side] = spread\n\ntitle = \"slope-basic · python · bokeh · anyplot.ai\"\np = figure(\n    width=3200,\n    height=1800,\n    title=title,\n    x_range=(-0.5, 1.5),\n    y_range=(28, 100),\n    toolbar_location=None,\n    min_border_bottom=100,\n    min_border_left=180,\n    min_border_top=110,\n    min_border_right=260,\n)\n\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None\n\np.title.text_font = \"helvetica\"\np.title.text_font_size = \"50pt\"\np.title.align = \"center\"\np.title.text_color = INK\n\np.xaxis.visible = False\np.yaxis.axis_label = \"Sales (thousands)\"\np.yaxis.axis_label_text_font = \"helvetica\"\np.yaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_color = INK\np.yaxis.major_label_text_font = \"helvetica\"\np.yaxis.major_label_text_font_size = \"34pt\"\np.yaxis.major_label_text_color = INK_SOFT\np.yaxis.axis_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_SOFT\np.ygrid.grid_line_alpha = 0.10\n\n# Time point column labels\nfor x_pos, label in [(0, \"Q1\"), (1, \"Q4\")]:\n    p.add_layout(\n        Label(\n            x=x_pos, y=30, text=label, text_font_size=\"28pt\", text_align=\"center\", text_baseline=\"top\", text_color=INK\n        )\n    )\n\n# ColumnDataSource for scatter enables HoverTool\nscatter_data: dict[str, list] = {\"x\": [], \"y\": [], \"color\": [], \"product\": [], \"period\": [], \"value\": []}\nfor product, start, end, color in zip(products, q1_sales, q4_sales, colors, strict=True):\n    scatter_data[\"x\"].extend([0, 1])\n    scatter_data[\"y\"].extend([start, end])\n    scatter_data[\"color\"].extend([color, color])\n    scatter_data[\"product\"].extend([product, product])\n    scatter_data[\"period\"].extend([\"Q1\", \"Q4\"])\n    scatter_data[\"value\"].extend([start, end])\n\nsource = ColumnDataSource(data=scatter_data)\n\n# Draw slope lines (legend_label merges same-labeled renderers into one entry)\n# and endpoint labels. Label TEXT uses the theme-tuned label_color (WCAG-safe)\n# while the line/marker keeps the true Imprint color for palette identity.\nfor i, (product, start, end, color, label_color, direction) in enumerate(\n    zip(products, q1_sales, q4_sales, colors, label_colors, directions, strict=True)\n):\n    p.line(x=[0, 1], y=[start, end], line_width=4, line_color=color, line_alpha=0.85, legend_label=direction)\n    p.add_layout(\n        Label(\n            x=-0.05,\n            y=label_ys[\"left\"][i],\n            text=f\"{product}: {start}\",\n            text_font_size=\"18pt\",\n            text_align=\"right\",\n            text_baseline=\"middle\",\n            text_color=label_color,\n        )\n    )\n    p.add_layout(\n        Label(\n            x=1.05,\n            y=label_ys[\"right\"][i],\n            text=f\"{end}: {product}\",\n            text_font_size=\"18pt\",\n            text_align=\"left\",\n            text_baseline=\"middle\",\n            text_color=label_color,\n        )\n    )\n\ndots = p.scatter(x=\"x\", y=\"y\", size=18, color=\"color\", source=source, alpha=0.9)\np.add_tools(\n    HoverTool(\n        renderers=[dots], tooltips=[(\"Product\", \"@product\"), (\"Period\", \"@period\"), (\"Sales\", \"@value{0} thousand\")]\n    )\n)\n\n# Move the auto-built direction legend outside the plot frame (right sidebar)\n# so it no longer eats vertical space between the title and the data, unlike\n# the previous floating in-frame label block.\np.legend.title = \"Direction\"\np.legend.title_text_font = \"helvetica\"\np.legend.title_text_font_size = \"26pt\"\np.legend.title_text_color = INK\np.legend.label_text_font = \"helvetica\"\np.legend.label_text_font_size = \"26pt\"\np.legend.label_text_color = INK_SOFT\np.legend.background_fill_color = ELEVATED_BG\np.legend.border_line_color = INK_SOFT\np.legend.glyph_width = 60\np.legend.glyph_height = 40\np.legend.spacing = 20\np.legend.padding = 20\np.add_layout(p.legend[0], \"right\")\n\noutput_file(f\"plot-{THEME}.html\", title=title)\nsave(p)\n\n# bokeh's export_png is unreliable in this environment (probes a chromedriver\n# snap shim) — write the HTML then screenshot it with headless Chrome instead.\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)\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 (a phantom ~143px\n# title bar eats into it even headless), so innerHeight ends up short of H.\n# Override the viewport directly via CDP for an exact WxH capture.\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"}