svgqini-curve
Qini curve
If we treat the units with the highest predicted uplift first, how much more effect do we get than targeting at random?
How to read it
- Read x as the share targeted, highest predicted uplift first.
- Read y as the incremental gain.
- The area between a curve and the diagonal is its Qini: bigger is better.
- Callout 1: This model's gain curve.
- Callout 2: Random targeting.
- Callout 3: The best possible targeting.
Watch out
- Uplift needs randomized (or carefully adjusted) data to be trusted.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Curves named random/optimal (also perfect/oracle) are drawn as references; without a random curve, the line from the origin to the first model's end point is used.
- Qini coefficient (legend) = area between the model curve and the random line by the trapezoid rule over the model's points; the engine's RATE/AUUC values are reported separately.
# Qini curve — Codesplash Chart Lab (recipe "qini-curve")
# controls: defaults
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("qini-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["curve"] = pd.Categorical(df["curve"].astype("string"), categories=["Causal forest", "X-learner", "random", "optimal"])
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
F = "share of customers targeted"
GAIN = "incremental customers retained"
CURVE = "curve"
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values(F)))
fig, ax = plt.subplots(figsize=(8, 4.5))
k = 0
for name, d in series:
low = str(name).lower()
if "random" in low:
ax.plot(d[F], d[GAIN], color=REF, linestyle="--", linewidth=1, label=name)
elif any(w in low for w in ("optimal", "perfect", "oracle")):
ax.plot(d[F], d[GAIN], color="grey", linestyle=":", linewidth=1.4, label=name)
else:
ax.plot(d[F], d[GAIN], color=PALETTE[k % len(PALETTE)], linewidth=2, label=name or GAIN)
k += 1
if not any("random" in str(n).lower() for n, _ in series):
end = series[0][1].iloc[-1]
ax.plot([0, end[F]], [0, end[GAIN]], color=REF, linestyle="--", linewidth=1, label="random targeting")
ax.set_xlabel(F)
ax.set_ylabel(GAIN)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads qini-curve-demo.csv · app theme from the optional codesplash helper
# Qini curve — Codesplash Chart Lab (recipe "qini-curve")
# controls: defaults
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("qini-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["curve"] = pd.Categorical(df["curve"].astype("string"), categories=["Causal forest", "X-learner", "random", "optimal"])
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
F = "share of customers targeted"
GAIN = "incremental customers retained"
CURVE = "curve"
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values(F)))
fig = go.Figure()
k = 0
for name, d in series:
low = str(name).lower()
ref = "random" in low or any(w in low for w in ("optimal", "perfect", "oracle"))
line = dict(color=REF if "random" in low else "grey", dash="dash" if "random" in low else "dot") if ref else dict(color=PALETTE[k % len(PALETTE)], width=2.5)
fig.add_scatter(x=d[F], y=d[GAIN], mode="lines", name=name or GAIN, line=line)
k += 0 if ref else 1
fig.update_layout(xaxis_title=F, yaxis_title=GAIN)
fig.show()Needs pandas, numpy, plotly · reads qini-curve-demo.csv · app theme from the optional codesplash helper
# Qini curve — Codesplash Chart Lab (recipe "qini-curve")
# controls: defaults
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("qini-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["curve"]] <- factor(df[["curve"]], levels = c("Causal forest", "X-learner", "random", "optimal"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
f_col <- "share of customers targeted"
gain_col <- "incremental customers retained"
curve_col <- "curve"
d <- data.frame(f = df[[f_col]], gain = df[[gain_col]], curve = if (is.null(curve_col)) "model" else as.character(df[[curve_col]]))
d <- d[!is.na(d$f) & !is.na(d$gain), ]
d$curve <- factor(d$curve, levels = unique(d$curve))
d$ref <- grepl("random|optimal|perfect|oracle", tolower(d$curve))
p <- ggplot(d, aes(f, gain, colour = curve, linetype = ref)) + geom_line(linewidth = 0.9) +
scale_colour_manual(values = c(cs_cat, ref_col, "grey50")) + scale_linetype_manual(values = c("solid", "dashed"), guide = "none") +
labs(x = f_col, y = gain_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads qini-curve-demo.csv · app theme from the optional codesplashr helper