{"spec_id":"bubble-basic","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\nbubble-basic: Basic Bubble Chart\nLibrary: plotnine 0.15.8 | Python 3.13.15\nQuality: 89/100 | Updated: 2026-09-27\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_point,\n    geom_smooth,\n    ggplot,\n    guide_legend,\n    labs,\n    scale_color_manual,\n    scale_fill_manual,\n    scale_size_area,\n    scale_x_continuous,\n    scale_y_continuous,\n    theme,\n    theme_minimal,\n)\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\"\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Data — countries across 4 regions: GDP per capita, life expectancy, population\nnp.random.seed(42)\n\nregions = [\"Asia-Pacific\", \"Europe\", \"Americas\", \"Middle East & Africa\"]\nregion_params = {\n    \"Asia-Pacific\": {\"n\": 18, \"gdp_mean\": 25, \"gdp_std\": 18, \"le_base\": 72, \"pop_mean\": 3.6},\n    \"Europe\": {\"n\": 18, \"gdp_mean\": 45, \"gdp_std\": 15, \"le_base\": 78, \"pop_mean\": 2.6},\n    \"Americas\": {\"n\": 18, \"gdp_mean\": 30, \"gdp_std\": 20, \"le_base\": 70, \"pop_mean\": 3.2},\n    \"Middle East & Africa\": {\"n\": 18, \"gdp_mean\": 12, \"gdp_std\": 10, \"le_base\": 62, \"pop_mean\": 3.0},\n}\n\nrows = []\nfor region, p in region_params.items():\n    gdp = np.abs(np.random.normal(p[\"gdp_mean\"], p[\"gdp_std\"], p[\"n\"]))\n    gdp = np.clip(gdp, 3, 85)\n    le = p[\"le_base\"] + 0.15 * gdp + np.random.normal(0, 2.5, p[\"n\"])\n    le = np.clip(le, 52, 88)\n    # Clip to a raised size-value floor (18-100, within the spec's 10-100 band) so\n    # even the smallest bubble renders with a clearly visible radius at max_size=18\n    pop = np.random.lognormal(mean=p[\"pop_mean\"], sigma=0.55, size=p[\"n\"])\n    pop = np.clip(pop, 18, 100)\n    for i in range(p[\"n\"]):\n        rows.append({\"gdp_per_capita\": gdp[i], \"life_expectancy\": le[i], \"population\": pop[i], \"region\": region})\n\ndf = pd.DataFrame(rows)\ndf[\"region\"] = pd.Categorical(df[\"region\"], categories=regions, ordered=True)\n\n# Plot\nplot = (\n    ggplot(df, aes(x=\"gdp_per_capita\", y=\"life_expectancy\", size=\"population\", fill=\"region\"))\n    # Per-region fit (color/fill mapped to region) instead of one pooled trend line —\n    # shows each region's own GDP/life-expectancy slope and confidence band rather than\n    # flattening the four groups into a single line. show_legend=False keeps the legend\n    # limited to the bubble fill key (same scale, so colors already match).\n    + geom_smooth(\n        aes(x=\"gdp_per_capita\", y=\"life_expectancy\", color=\"region\", fill=\"region\"),\n        method=\"lm\",\n        se=True,\n        alpha=0.08,\n        size=0.8,\n        inherit_aes=False,\n        show_legend=False,\n    )\n    # geom_point's default shape already splits fill (region color) from edge\n    # (color); fixing color to the page bg gives each bubble a subtle halo that\n    # separates it from overlapping neighbors. alpha lowered further (0.55 -> 0.45)\n    # to keep the densest cluster (Middle East & Africa, ~$15-20k GDP) from merging\n    # into a single blob.\n    + geom_point(color=PAGE_BG, alpha=0.45, stroke=0.5)\n    # limits=(0, 100) anchors the area scaling to a true zero baseline; without it\n    # plotnine anchors the sqrt-area formula to the data's own min, which maps the\n    # smallest (floor-clipped) bubbles to a near-zero rendered size. max_size trimmed\n    # from 18 to 15 so the largest bubbles overlap less severely in dense clusters.\n    # override_aes gives the size-legend's key glyphs a visible INK_SOFT fill/edge —\n    # without it they'd inherit geom_point's fixed color=PAGE_BG stroke, which blends\n    # into the PAGE_BG legend_key background and renders as empty boxes.\n    + scale_size_area(\n        max_size=15,\n        breaks=[20, 50, 90],\n        limits=(0, 100),\n        name=\"Population (M)\",\n        guide=guide_legend(override_aes={\"fill\": INK_SOFT, \"color\": INK_SOFT, \"alpha\": 1}),\n    )\n    + scale_fill_manual(values=IMPRINT_PALETTE[:4], name=\"Region\")\n    + scale_color_manual(values=IMPRINT_PALETTE[:4], guide=None)\n    + scale_x_continuous(labels=lambda lst: [f\"${v:.0f}k\" for v in lst], breaks=[10, 20, 30, 40, 50, 60, 70, 80])\n    + scale_y_continuous(labels=lambda lst: [f\"{v:.0f}\" for v in lst])\n    + labs(\n        x=\"GDP per Capita (USD thousands)\",\n        y=\"Life Expectancy (years)\",\n        title=\"bubble-basic · python · plotnine · anyplot.ai\",\n        subtitle=\"Each region's own GDP-to-life-expectancy trend, with population size layered on top\",\n    )\n    + theme_minimal()\n    + theme(\n        figure_size=(8, 4.5),\n        plot_margin_right=0.025,\n        text=element_text(size=7, color=INK_SOFT),\n        axis_title=element_text(size=10, color=INK),\n        axis_text=element_text(size=8, color=INK_SOFT),\n        plot_title=element_text(size=12, color=INK),\n        plot_subtitle=element_text(size=8, color=INK_SOFT),\n        legend_title=element_text(size=8, color=INK),\n        legend_text=element_text(size=8, color=INK_SOFT),\n        legend_key=element_rect(fill=PAGE_BG, color=\"none\"),\n        legend_background=element_rect(fill=ELEVATED_BG, color=\"none\"),\n        panel_grid_major=element_line(color=INK, size=0.3, alpha=0.15),\n        panel_grid_minor=element_blank(),\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG, color=\"none\"),\n        panel_border=element_blank(),\n        axis_line=element_line(color=INK_SOFT),\n    )\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\", verbose=False)\n"}