{"spec_id":"bubble-basic","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\nbubble-basic: Basic Bubble Chart\nLibrary: seaborn 0.13.2 | Python 3.13.15\nQuality: 92/100 | Updated: 2026-09-27\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.ticker import FuncFormatter\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 palette — canonical order, first series always #009E73\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Data — Countries: healthcare spending vs child mortality, bubble = population\nnp.random.seed(42)\n\ntier_params = [\n    (\"Low Income\", 35, 380, 85, 30, 15),\n    (\"Lower-Middle Income\", 380, 950, 38, 11, 15),\n    (\"Upper-Middle Income\", 950, 3200, 14, 5, 15),\n    (\"High Income\", 3200, 8500, 5, 2, 15),\n]\ntier_colors = {t[0]: IMPRINT_PALETTE[i] for i, t in enumerate(tier_params)}\n\nrows = []\nfor tier, s_min, s_max, m_ctr, m_std, n in tier_params:\n    spending = np.random.uniform(s_min, s_max, n)\n    mortality = np.clip(np.random.normal(m_ctr, m_std, n), 0.5, 150)\n    population = np.clip(np.random.lognormal(3.1, 0.35, n), 10.0, 100.0)\n    for s, m, pop in zip(spending, mortality, population, strict=False):\n        rows.append(\n            {\n                \"Healthcare Spending ($/year)\": round(s, 0),\n                \"Child Mortality (per 1,000 births)\": round(m, 1),\n                \"Population (M)\": round(pop, 1),\n                \"Income Tier\": tier,\n            }\n        )\ndf = pd.DataFrame(rows)\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\n# Plot\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\nhue_order = [t[0] for t in tier_params]\n\n# Subtle lowess trend line — makes the inverse spending/mortality\n# relationship an explicit visual cue without adding a text callout\nsns.regplot(\n    data=df,\n    x=\"Healthcare Spending ($/year)\",\n    y=\"Child Mortality (per 1,000 births)\",\n    scatter=False,\n    lowess=True,\n    ax=ax,\n    color=INK_SOFT,\n    line_kws={\"linewidth\": 1.6, \"linestyle\": \"--\", \"alpha\": 0.55},\n)\n\nsns.scatterplot(\n    data=df,\n    x=\"Healthcare Spending ($/year)\",\n    y=\"Child Mortality (per 1,000 births)\",\n    size=\"Population (M)\",\n    hue=\"Income Tier\",\n    hue_order=hue_order,\n    sizes=(50, 650),\n    alpha=0.58,\n    palette=tier_colors,\n    edgecolor=PAGE_BG,\n    linewidth=1.0,\n    legend=\"brief\",\n    ax=ax,\n)\n\n# Style\ntitle = \"bubble-basic · python · seaborn · anyplot.ai\"\nn_chars = len(title)\nratio = 67 / n_chars if n_chars > 67 else 1.0\ntitle_fontsize = max(8, round(12 * ratio))\n\nax.set_xlabel(\"Healthcare Spending ($ / year)\", fontsize=10, color=INK)\nax.set_ylabel(\"Child Mortality (per 1,000 births)\", fontsize=10, color=INK)\nax.set_title(title, fontsize=title_fontsize, fontweight=\"medium\", color=INK)\n\n# Spending spans two orders of magnitude across tiers, so a linear x-axis\n# crushes the Low Income cluster into a sliver; log scale spaces every tier\n# evenly and separates its 15 points instead.\nax.set_xscale(\"log\")\nax.set_xticks([100, 300, 1000, 3000, 8000])\nax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: f\"{x:,.0f}\"))\nax.xaxis.set_minor_formatter(FuncFormatter(lambda x, _: \"\"))\n\nax.tick_params(axis=\"both\", labelsize=8, colors=INK_SOFT, length=0)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"left\"].set_color(INK_SOFT)\nax.spines[\"bottom\"].set_color(INK_SOFT)\nax.yaxis.grid(True, alpha=0.15, linewidth=0.8)\nax.xaxis.grid(True, alpha=0.15, linewidth=0.8)\n\n# Move legend first, then configure the resulting object to avoid losing changes.\n# Tightened padding (borderpad/labelspacing/handletextpad) and a smaller\n# markerscale keep the combined hue+size legend from dominating the upper-right\n# quadrant, since the size legend's largest swatch tracks the 650pt max marker.\nsns.move_legend(ax, \"upper right\", frameon=True, borderpad=0.5, labelspacing=0.35, handletextpad=0.5, markerscale=0.85)\nlegend = ax.get_legend()\nlegend.set_title(\"Income Tier / Population (M)\", prop={\"size\": 8})\nlegend.get_title().set_fontweight(\"semibold\")\nlegend.get_title().set_color(INK)\ntier_names = {t[0] for t in tier_params}\nfor handle, text_obj in zip(legend.legend_handles, legend.texts, strict=False):\n    text_obj.set_fontsize(8)\n    text_obj.set_color(INK)\n    # Size handles (non-tier labels): the combined hue+size legend renders these\n    # as Line2D markers, not patches, so recolor via the marker face/edge setters.\n    # alpha is set explicitly to 1.0 (not inherited from the scatter's alpha=0.58)\n    # so the swatch stays legible against the dark elevated panel.\n    if text_obj.get_text() not in tier_names:\n        handle.set_markerfacecolor(INK_SOFT)\n        handle.set_markeredgecolor(INK_SOFT)\n        handle.set_alpha(1.0)\nlegend.set_frame_on(True)\nlegend.get_frame().set_alpha(0.92)\nlegend.get_frame().set_edgecolor(INK_SOFT)\nlegend.get_frame().set_facecolor(ELEVATED_BG)\n\n# Save — no bbox_inches='tight' to preserve exact 3200×1800 canvas\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}