{"spec_id":"bar-diverging","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\nbar-diverging: Diverging Bar Chart\nLibrary: seaborn 0.13.2 | Python 3.13.15\nQuality: 91/100 | Updated: 2026-08-18\n\"\"\"\n\nimport os\nimport sys\n\n\nsys.path = [p for p in sys.path if \"implementations\" not in p]\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\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 semantic anchors — profit/loss is a labeled sentiment pair, so we\n# break canonical ordinal order (see default-style-guide.md \"Semantic exception\")\nPROFIT_COLOR = \"#009E73\"  # Imprint position 1 — brand green, profit\nLOSS_COLOR = \"#AE3030\"  # Imprint position 5 — matte red, loss\n\n# Data - Quarterly profit/loss by business unit (in millions)\nunits = [\n    \"Cloud Services\",\n    \"Data Analytics\",\n    \"AI Solutions\",\n    \"DevOps Platform\",\n    \"Security Suite\",\n    \"Enterprise Integration\",\n    \"Mobile Apps\",\n    \"Edge Computing\",\n    \"Cybersecurity\",\n    \"Support Services\",\n]\nvalues = np.array([42, -18, 65, -25, 38, -12, 28, 52, -8, 15])\n\ndf = pd.DataFrame({\"Unit\": units, \"Value\": values})\ndf[\"Sign\"] = np.where(df[\"Value\"] >= 0, \"Profit\", \"Loss\")\ndf = df.sort_values(\"Value\", ascending=True).reset_index(drop=True)\n\n# Configure seaborn theme\nsns.set_theme(\n    style=\"ticks\",\n    rc={\n        \"figure.facecolor\": PAGE_BG,\n        \"axes.facecolor\": PAGE_BG,\n        \"axes.edgecolor\": INK_SOFT,\n        \"axes.labelcolor\": INK,\n        \"text.color\": INK,\n        \"xtick.color\": INK_SOFT,\n        \"ytick.color\": INK_SOFT,\n        \"grid.color\": INK,\n        \"grid.alpha\": 0.15,\n        \"legend.facecolor\": ELEVATED_BG,\n        \"legend.edgecolor\": INK_SOFT,\n    },\n)\n\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\n\n# Idiomatic seaborn: hue-mapped palette instead of a manual color list,\n# dodge=False since each Unit already owns a single row/bar.\nsns.barplot(\n    data=df,\n    x=\"Value\",\n    y=\"Unit\",\n    hue=\"Sign\",\n    hue_order=[\"Profit\", \"Loss\"],\n    palette={\"Profit\": PROFIT_COLOR, \"Loss\": LOSS_COLOR},\n    dodge=False,\n    ax=ax,\n    orient=\"h\",\n)\n\n# Zero baseline uses the theme-adaptive neutral anchor — it's structural,\n# not data, so it reads as part of the chart's chrome layer.\nax.axvline(x=0, color=INK, linewidth=1.2, zorder=2)\n\n# Direct value labels at each bar tip — bolded for the best/worst performer\n# to give the chart a focal point beyond \"well-configured default\".\nidx_best = df[\"Value\"].idxmax()\nidx_worst = df[\"Value\"].idxmin()\nspan = df[\"Value\"].max() - df[\"Value\"].min()\nlabel_pad = span * 0.015\nfor i, row in df.iterrows():\n    val = row[\"Value\"]\n    highlight = i in (idx_best, idx_worst)\n    ax.text(\n        val + (label_pad if val >= 0 else -label_pad),\n        i,\n        f\"{val:+.0f}\",\n        va=\"center\",\n        ha=\"left\" if val >= 0 else \"right\",\n        fontsize=8.5 if highlight else 8,\n        fontweight=\"bold\" if highlight else \"regular\",\n        color=INK if highlight else INK_SOFT,\n    )\n\n# Callout: net total across all units — a single narrative summary number\n# anchored away from the bars, in the elevated-surface treatment used for\n# legend/annotation boxes.\nnet_total = df[\"Value\"].sum()\nax.annotate(\n    f\"Net Q1: {net_total:+.0f}M\",\n    xy=(0.985, 0.965),\n    xycoords=\"axes fraction\",\n    ha=\"right\",\n    va=\"top\",\n    fontsize=9,\n    fontweight=\"medium\",\n    color=INK,\n    bbox={\"boxstyle\": \"round,pad=0.4\", \"facecolor\": ELEVATED_BG, \"edgecolor\": INK_SOFT, \"linewidth\": 0.8},\n)\n\n# Style\nax.set_xlabel(\"Profit / Loss ($ Millions)\", fontsize=10, color=INK)\nax.set_ylabel(\"Business Unit\", fontsize=10, color=INK)\nax.set_title(\"bar-diverging · seaborn · anyplot.ai\", fontsize=12, fontweight=\"medium\", color=INK)\nax.tick_params(axis=\"both\", labelsize=8, colors=INK_SOFT)\nax.margins(x=0.12)\n\n# Grid on x-axis only\nax.xaxis.grid(True, alpha=0.15, linewidth=0.8)\nax.yaxis.grid(False)\nax.set_axisbelow(True)\n\nsns.despine(ax=ax, top=True, right=True)\nax.spines[\"left\"].set_color(INK_SOFT)\nax.spines[\"bottom\"].set_color(INK_SOFT)\n\nlegend = ax.legend(loc=\"upper right\", bbox_to_anchor=(0.985, 0.78), frameon=True, fontsize=8, title=None)\nlegend.get_frame().set_facecolor(ELEVATED_BG)\nlegend.get_frame().set_edgecolor(INK_SOFT)\nfor text in legend.get_texts():\n    text.set_color(INK)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}