svgimportance-bar
Feature importance
Which features does the model rely on most?
How to read it
- Read bar length as how much the model relies on that feature.
- Check the whiskers: overlapping features may not really differ.
- Check which kind of importance is on the axis.
- Callout 1: The top feature.
- Callout 2: Whisker: how much it varies across repeats.
- Callout 3: Near zero: the model barely uses these.
Watch out
- Importance doesn't mean causal, and correlated features share or swap importance.
Defaults
- Features shown
- 20
- How many features to show, largest first.
- Range 3 to 60, step 1
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Ranked by |importance|; negative permutation importance (the model did better with the feature shuffled) is drawn left of zero in a second colour.
- Importance kinds are not comparable across methods: gain counts splits, permutation measures the metric drop, SHAP the mean absolute contribution — the axis label names the kind.
- Correlated features share importance; a low value does not mean the feature carries no information.
# Feature importance — Codesplash Chart Lab (recipe "importance-bar")
# controls: top=20
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("importance-bar-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["tenure (months)", "monthly charges", "contract=month-to-month", "support calls", "total charges", "payment=electronic check", "age", "internet=fiber", "streaming TV", "paperless billing", "dependents", "region=north"])
FEAT = "feature"
IMP = "drop in ROC AUC"
LO = "lower"
HI = "upper"
TOP = 20
d = df.dropna(subset=[FEAT, IMP]).sort_values(IMP, ascending=False).head(TOP).iloc[::-1] # largest at the top
fig, ax = plt.subplots(figsize=(8, 0.32 * len(d) + 1.2))
err = [d[IMP] - d[LO], d[HI] - d[IMP]] if LO and HI else None
ax.barh(d[FEAT].astype(str), d[IMP], xerr=err, color=PALETTE[0], ecolor="grey", capsize=2)
ax.axvline(0, color="grey", linewidth=0.8)
ax.set_xlabel(IMP)
plt.show()Needs pandas, numpy, matplotlib · reads importance-bar-demo.csv · app theme from the optional codesplash helper
# Feature importance — Codesplash Chart Lab (recipe "importance-bar")
# controls: top=20
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("importance-bar-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["tenure (months)", "monthly charges", "contract=month-to-month", "support calls", "total charges", "payment=electronic check", "age", "internet=fiber", "streaming TV", "paperless billing", "dependents", "region=north"])
FEAT = "feature"
IMP = "drop in ROC AUC"
LO = "lower"
HI = "upper"
TOP = 20
d = df.dropna(subset=[FEAT, IMP]).sort_values(IMP, ascending=False).head(TOP).iloc[::-1]
err = dict(type="data", symmetric=False, array=d[HI] - d[IMP], arrayminus=d[IMP] - d[LO]) if LO and HI else None
fig = go.Figure(go.Bar(x=d[IMP], y=d[FEAT].astype(str), orientation="h", marker_color=PALETTE[0], error_x=err))
fig.update_layout(xaxis_title=IMP, yaxis_title=None)
fig.show()Needs pandas, numpy, plotly · reads importance-bar-demo.csv · app theme from the optional codesplash helper
# Feature importance — Codesplash Chart Lab (recipe "importance-bar")
# controls: top=20
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("importance-bar-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feature"]] <- factor(df[["feature"]], levels = c("tenure (months)", "monthly charges", "contract=month-to-month", "support calls", "total charges", "payment=electronic check", "age", "internet=fiber", "streaming TV", "paperless billing", "dependents", "region=north"))
feat_col <- "feature"
imp_col <- "drop in ROC AUC"
lo_col <- "lower"
hi_col <- "upper"
top_n <- 20
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[imp_col]]), ]
d <- data.frame(f = as.character(d[[feat_col]]), v = d[[imp_col]], lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]])
d <- head(d[order(-d$v), ], top_n)
d$f <- factor(d$f, levels = rev(d$f)) # largest at the top
p <- ggplot(d, aes(v, f)) + geom_col(fill = cs_cat[1], width = 0.7) +
{ if (!all(is.na(d$lo))) geom_errorbar(aes(xmin = lo, xmax = hi), width = 0.25, colour = "grey45", orientation = "y") } +
geom_vline(xintercept = 0, colour = "grey60") + labs(x = imp_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads importance-bar-demo.csv · app theme from the optional codesplashr helper