{"spec_id":"histogram-kde","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nhistogram-kde: Histogram with KDE Overlay\nLibrary: matplotlib 3.11.1 | Python 3.13.14\nQuality: 94/100 | Updated: 2026-08-05\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import gaussian_kde\n\n\n# Theme tokens (see prompts/default-style-guide.md \"Background\" + \"Theme-adaptive Chrome\")\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\"\nBRAND = \"#009E73\"  # Imprint palette position 1 — ALWAYS first series\nACCENT = \"#C475FD\"  # Imprint palette position 2 — KDE curve\n\n# Data - simulate stock daily returns blending calm, volatile, and tail-risk regimes\nnp.random.seed(42)\nnormal_returns = np.random.normal(0.0005, 0.015, 800)\nvolatile_returns = np.random.normal(-0.002, 0.035, 150)\nextreme_returns = np.random.normal(0.001, 0.05, 50)\nreturns = np.concatenate([normal_returns, volatile_returns, extreme_returns]) * 100\nnp.random.shuffle(returns)\nmean_return = returns.mean()\nvar_5 = np.percentile(returns, 5)  # 5% Value-at-Risk — marks the downside tail\n\n# Plot — see default-style-guide.md \"Visual Sizing Defaults\" for the canvas + sizing values\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Shade the downside tail-risk region (below the 5% VaR threshold) behind\n# everything else, using the matte-red semantic anchor reserved for loss/risk\nax.axvspan(returns.min() - 0.5, var_5, color=\"#AE3030\", alpha=0.08, zorder=0)\n\n# Histogram with density scaling (semi-transparent, brand color)\nax.hist(\n    returns,\n    bins=44,\n    density=True,\n    alpha=0.5,\n    color=BRAND,\n    edgecolor=PAGE_BG,\n    linewidth=0.6,\n    label=\"Histogram\",\n    zorder=2,\n)\n\n# KDE overlay using scipy, with a soft fill to give the curve visual weight\n# and separate it from the discrete bars beneath it\nkde = gaussian_kde(returns)\nx_range = np.linspace(returns.min() - 0.5, returns.max() + 0.5, 500)\nkde_values = kde(x_range)\npeak_density = kde_values.max()\nax.fill_between(x_range, kde_values, color=ACCENT, alpha=0.15, zorder=1)\nax.plot(x_range, kde_values, color=ACCENT, linewidth=2.5, label=\"KDE\", zorder=3)\n\n# Headroom above the KDE peak so callouts never overlap the curve\ny_top = peak_density * 1.35\nax.set_ylim(0, y_top)\n\n# Tail-risk callout inside the shaded region, clear of the histogram/KDE\nax.text(\n    (returns.min() - 0.5 + var_5) / 2,\n    y_top * 0.94,\n    \"tail risk\\n(5% VaR)\",\n    fontsize=7,\n    color=\"#AE3030\",\n    ha=\"center\",\n    va=\"top\",\n    linespacing=1.3,\n)\n\n# Mean reference line — draws the eye to the distribution's center of mass.\n# The label sits well above the KDE peak with a short leader line so it\n# never crowds the curve's apex.\nax.axvline(mean_return, color=INK_SOFT, linewidth=1.2, linestyle=\"--\", zorder=4)\nax.annotate(\n    f\"mean {mean_return:.2f}%\",\n    xy=(mean_return, peak_density),\n    xytext=(18, 30),\n    textcoords=\"offset points\",\n    fontsize=8,\n    color=INK_SOFT,\n    ha=\"left\",\n    va=\"bottom\",\n    arrowprops={\"arrowstyle\": \"-\", \"color\": INK_SOFT, \"linewidth\": 0.8, \"shrinkA\": 0, \"shrinkB\": 3},\n)\n\n# Style\ntitle = \"histogram-kde · python · matplotlib · anyplot.ai\"\nax.set_xlabel(\"Daily Return (%)\", fontsize=10, color=INK)\nax.set_ylabel(\"Density\", fontsize=10, color=INK)\nax.set_title(title, fontsize=12, fontweight=\"medium\", color=INK)\nax.tick_params(axis=\"both\", labelsize=8, colors=INK_SOFT)\nax.legend(fontsize=8, loc=\"upper right\")\nleg = ax.get_legend()\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\nax.yaxis.grid(True, alpha=0.15, linewidth=0.8, color=INK)\n\n# Save\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}