Skip to content
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?

Demo data · seed 20261101 · 84 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read x as the share targeted, highest predicted uplift first.
  2. Read y as the incremental gain.
  3. The area between a curve and the diagonal is its Qini: bigger is better.
  1. Callout 1: This model's gain curve.
  2. Callout 2: Random targeting.
  3. 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