svginfluence-index
Cook's distance by row
Which rows pull the fit the most?
How to read it
- Read each stem as how much the fit changes if you leave that row out.
- Compare with the dashed cutoff: rows above it are named.
- Look at those rows and find out why they differ.
- Callout 1: A named row, above the cutoff.
- Callout 2: The dashed line: the cutoff.
- Callout 3: Most rows have little pull.
Watch out
- An influential row isn't automatically wrong: don't delete it for being influential. Report the fit with and without it.
Defaults
- Cutoff
- 4 / n
- 4/n flags rows worth a look; 1 flags rows that shift the whole fit.
- Also: 1
Pinned in the code
- Bars (stems) from zero at each row's Cook's distance, as R's plot.lm(which = 4).
- A row above the cutoff is drawn in the warning colour and labelled.
# Cook's distance by row — Codesplash Chart Lab (recipe "influence-index")
# controls: rule=four
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("influence-index-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
D = "Cook's distance"
I = None
L = "row"
d = df.dropna(subset=[D]).reset_index(drop=True)
idx = d[I].to_numpy(float) if I else np.arange(1, len(d) + 1)
cut = 4 / len(d) # the 4/n convention
flag = d[D] > cut
fig, ax = plt.subplots(figsize=(7, 4))
ax.vlines(idx, 0, d[D], colors=[PALETTE[1] if f else PALETTE[0] for f in flag])
ax.axhline(cut, color=REF, linestyle="--", linewidth=1, label=f"cutoff {cut:.3g}")
for i in np.flatnonzero(flag)[:12]:
ax.annotate(str(d[L].iloc[i]) if L else str(int(idx[i])), (idx[i], d[D].iloc[i]), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8)
ax.set_xlabel("row")
ax.set_ylabel("Cook's distance")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads influence-index-demo.csv · app theme from the optional codesplash helper
# Cook's distance by row — Codesplash Chart Lab (recipe "influence-index")
# controls: rule=four
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("influence-index-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
D = "Cook's distance"
I = None
L = "row"
d = df.dropna(subset=[D]).reset_index(drop=True)
idx = d[I].to_numpy(float) if I else np.arange(1, len(d) + 1)
cut = 4 / len(d)
fig = go.Figure(go.Bar(x=idx, y=d[D], marker_color=[PALETTE[1] if v > cut else PALETTE[0] for v in d[D]], text=d[L] if L else None))
fig.add_hline(y=cut, line_dash="dash", line_color=REF, annotation_text=f"cutoff {cut:.3g}")
fig.update_layout(xaxis_title="row", yaxis_title="Cook's distance")
fig.show()Needs pandas, numpy, plotly · reads influence-index-demo.csv · app theme from the optional codesplash helper
# Cook's distance by row — Codesplash Chart Lab (recipe "influence-index")
# controls: rule=four
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("influence-index-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["row"]] <- factor(df[["row"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
D <- "Cook's distance"
I <- NULL
L <- "row"
d <- data.frame(cooks = df[[D]], label = if (is.null(L)) NA else as.character(df[[L]]))
d$index <- if (is.null(I)) seq_len(nrow(d)) else df[[I]]
d <- d[is.finite(d$cooks), ]
cut <- 4 / nrow(d)
d$flag <- d$cooks > cut
p <- ggplot(d, aes(index, cooks, colour = flag)) +
geom_segment(aes(xend = index, yend = 0)) +
geom_hline(yintercept = cut, colour = ref_col, linetype = "dashed") +
geom_text(aes(label = label), d[d$flag, ], vjust = -0.5, size = 2.8, show.legend = FALSE) +
scale_colour_manual(values = cs_cat[1:2], guide = "none") +
labs(x = "row", y = "Cook's distance") + theme_cs
print(p)Needs ggplot2 · reads influence-index-demo.csv · app theme from the optional codesplashr helper