{"spec_id":"bar-permutation-importance","library":"plotly","language":"python","code":"\"\"\" anyplot.ai\nbar-permutation-importance: Permutation Feature Importance Plot\nLibrary: plotly 6.7.0 | Python 3.13.13\nQuality: 94/100 | Updated: 2026-05-17\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\n\n\n# Theme configuration\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\"\nGRID = \"rgba(26,26,23,0.10)\" if THEME == \"light\" else \"rgba(240,239,232,0.10)\"\n\n# Data - Simulating permutation importance results from a regression model\nnp.random.seed(42)\n\n# Feature names representing typical ML model features\nfeatures = [\n    \"Temperature\",\n    \"Humidity\",\n    \"Wind Speed\",\n    \"Pressure\",\n    \"Solar Radiation\",\n    \"Precipitation\",\n    \"Cloud Cover\",\n    \"UV Index\",\n    \"Visibility\",\n    \"Dew Point\",\n    \"Air Quality Index\",\n    \"Altitude\",\n    \"Latitude\",\n    \"Season Encoded\",\n    \"Time of Day\",\n]\n\nn_features = len(features)\n\n# Generate realistic importance values (some high, some low, a couple negative)\nimportance_mean = np.array(\n    [0.245, 0.198, 0.156, 0.089, 0.072, 0.058, 0.045, 0.038, 0.025, 0.018, 0.012, 0.008, 0.003, -0.002, -0.008]\n)\n\n# Standard deviations vary - more important features often have higher variability\nimportance_std = np.array(\n    [0.045, 0.038, 0.032, 0.022, 0.018, 0.015, 0.012, 0.010, 0.008, 0.006, 0.005, 0.004, 0.003, 0.003, 0.004]\n)\n\n# Create DataFrame and sort by importance (highest first)\ndf = pd.DataFrame({\"feature\": features, \"importance_mean\": importance_mean, \"importance_std\": importance_std})\ndf = df.sort_values(\"importance_mean\", ascending=True)  # ascending for horizontal bar layout\n\n# Color using viridis colormap for continuous importance values\nmin_imp = df[\"importance_mean\"].min()\nmax_imp = df[\"importance_mean\"].max()\nimp_range = max_imp - min_imp\n\n# Normalize importance to [0, 1] range for colormap\nnormalized_values = (df[\"importance_mean\"] - min_imp) / imp_range if imp_range > 0 else np.zeros(len(df))\n\n# Create viridis-like colors (blue to yellow gradient)\nviridis_colors = [\n    f\"rgba({int(68 + (229 - 68) * v)}, {int(1 + (194 - 1) * v)}, {int(84 + (30 - 84) * v)}, 0.85)\"\n    for v in normalized_values\n]\n\n# Create figure\nfig = go.Figure()\n\n# Add horizontal bars with viridis coloring\nfig.add_trace(\n    go.Bar(\n        x=df[\"importance_mean\"],\n        y=df[\"feature\"],\n        orientation=\"h\",\n        marker=dict(color=viridis_colors),\n        error_x=dict(type=\"data\", array=df[\"importance_std\"], color=INK_SOFT, thickness=2, width=6),\n        hovertemplate=\"<b>%{y}</b><br>Importance: %{x:.3f}<extra></extra>\",\n        showlegend=False,\n    )\n)\n\n# Add vertical reference line at x=0\nfig.add_vline(x=0, line=dict(color=INK_SOFT, width=2, dash=\"dash\"))\n\n# Add annotations for top 3 features\ntop_features_idx = df.nlargest(3, \"importance_mean\").index\nfor idx in top_features_idx:\n    row = df.loc[idx]\n    fig.add_annotation(\n        x=row[\"importance_mean\"],\n        y=row[\"feature\"],\n        text=f\"{row['importance_mean']:.3f}\",\n        showarrow=False,\n        xanchor=\"left\",\n        xshift=8,\n        font=dict(size=16, color=INK_SOFT),\n    )\n\n# Update layout with theme-adaptive colors\nfig.update_layout(\n    title=dict(\n        text=\"bar-permutation-importance · plotly · pyplots.ai\", font=dict(size=32, color=INK), x=0.5, xanchor=\"center\"\n    ),\n    xaxis=dict(\n        title=dict(text=\"Mean Decrease in Model Score (R² loss)\", font=dict(size=22, color=INK)),\n        tickfont=dict(size=18, color=INK_SOFT),\n        gridcolor=GRID,\n        gridwidth=1,\n        zeroline=False,\n        linecolor=INK_SOFT,\n        showgrid=True,\n    ),\n    yaxis=dict(\n        title=dict(text=\"Feature\", font=dict(size=22, color=INK)),\n        tickfont=dict(size=18, color=INK_SOFT),\n        linecolor=INK_SOFT,\n        showgrid=False,\n    ),\n    plot_bgcolor=PAGE_BG,\n    paper_bgcolor=PAGE_BG,\n    margin=dict(l=200, r=100, t=100, b=80),\n    showlegend=False,\n    font=dict(color=INK),\n)\n\n# Save as PNG (4800x2700 via scale=3)\nfig.write_image(f\"plot-{THEME}.png\", width=1600, height=900, scale=3)\n\n# Save interactive HTML\nfig.write_html(f\"plot-{THEME}.html\", include_plotlyjs=\"cdn\")\n"}