{"spec_id":"bar-feature-importance","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\nbar-feature-importance: Feature Importance Bar Chart\nLibrary: seaborn 0.13.2 | Python 3.13.13\nQuality: 85/100 | Updated: 2026-05-10\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\n# Data: Simulated feature importances from a Random Forest model\nnp.random.seed(42)\n\nfeatures = [\n    \"Annual Income\",\n    \"Credit Score\",\n    \"Employment Years\",\n    \"Debt-to-Income Ratio\",\n    \"Age\",\n    \"Number of Accounts\",\n    \"Loan Amount\",\n    \"Payment History\",\n    \"Credit Utilization\",\n    \"Home Ownership\",\n    \"Education Level\",\n    \"Marital Status\",\n    \"Monthly Expenses\",\n    \"Savings Balance\",\n    \"Previous Defaults\",\n]\n\n# Generate realistic importance values (sum to 1.0 for interpretability)\nraw_importance = np.array([0.18, 0.15, 0.12, 0.11, 0.09, 0.08, 0.07, 0.06, 0.05, 0.03, 0.02, 0.015, 0.01, 0.008, 0.007])\nimportance = raw_importance / raw_importance.sum()\n\n# Standard deviation for error bars (ensemble variability)\nstd = np.random.uniform(0.005, 0.025, len(features))\n\n# Create DataFrame and sort by importance\ndf = pd.DataFrame({\"feature\": features, \"importance\": importance, \"std\": std})\ndf = df.sort_values(\"importance\", ascending=True).reset_index(drop=True)\n\n# Create figure\nfig, ax = plt.subplots(figsize=(16, 9))\n\n# Create color palette based on importance values (sequential gradient)\ncolors = sns.color_palette(\"Blues\", n_colors=len(df))\n\n# Plot horizontal bars using seaborn\nsns.barplot(\n    data=df,\n    x=\"importance\",\n    y=\"feature\",\n    hue=\"feature\",\n    palette=colors,\n    legend=False,\n    ax=ax,\n    edgecolor=\"#306998\",\n    linewidth=1.5,\n)\n\n# Add error bars manually for ensemble variability\nax.errorbar(\n    df[\"importance\"], range(len(df)), xerr=df[\"std\"], fmt=\"none\", color=\"#306998\", capsize=4, capthick=2, linewidth=2\n)\n\n# Add value annotations at the end of bars\nfor i, (imp, std_val) in enumerate(zip(df[\"importance\"], df[\"std\"], strict=True)):\n    ax.text(\n        imp + std_val + 0.008, i, f\"{imp:.3f}\", va=\"center\", ha=\"left\", fontsize=14, color=\"#306998\", fontweight=\"bold\"\n    )\n\n# Styling\nax.set_xlabel(\"Feature Importance\", fontsize=20)\nax.set_ylabel(\"Feature\", fontsize=20)\nax.set_title(\"bar-feature-importance · seaborn · pyplots.ai\", fontsize=24, fontweight=\"bold\", pad=20)\nax.tick_params(axis=\"both\", labelsize=16)\nax.set_xlim(0, df[\"importance\"].max() + df[\"std\"].max() + 0.05)\n\n# Subtle grid on x-axis only\nax.grid(True, axis=\"x\", alpha=0.3, linestyle=\"--\")\nax.set_axisbelow(True)\n\n# Remove top and right spines for cleaner look\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n\nplt.tight_layout()\nplt.savefig(\"plot.png\", dpi=300, bbox_inches=\"tight\")\n"}