svglorenz-gini
Lorenz curve and Gini
How unevenly is the total lifetime shared out among units?
How to read it
- Read x as the share of units, shortest-lived first, and y as their share of all the lifetime in the sample.
- Compare the curve with the dashed exponential curve, whose Gini is one half.
- Further below it means lifetimes are more unequal, which points to a falling failure rate; above it, a rising one.
- Callout 1: The line of equality: every unit lasts equally long.
- Callout 2: The exponential reference, Gini one half.
- Callout 3: The sample's curve, and the Gini is twice the area between it and equality.
Watch out
- It compares lifetimes with each other, so it ignores the time scale. Two samples with very different mean lives can share a curve.
Defaults
- Exponential reference
- On
- Show the Lorenz curve of an exponential distribution.
Pinned in the code
- Curve: (i/n, Σ_{j≤i} x_(j) / Σ x). Gini: ΣΣ|x_i − x_j| / (2n(n−1)x̄), the finite-sample normalization of the guide's entry 145.
- The exponential reference is L(p) = p + (1 − p) log(1 − p).
# Lorenz curve and Gini — Codesplash Chart Lab (recipe "lorenz-gini")
# controls: reference=true
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("lorenz-gini-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")
V = "hours"
x = np.sort(df[V].dropna().to_numpy(dtype=float))
n = x.size
p_ = np.concatenate(([0.0], np.arange(1, n + 1) / n))
l_ = np.concatenate(([0.0], np.cumsum(x) / x.sum()))
gini = 2 * np.sum((2 * np.arange(1, n + 1) - n - 1) * x) / (2 * n * (n - 1) * x.mean())
grid = np.linspace(0, 0.999, 60)
ref = grid + (1 - grid) * np.log1p(-grid) # exponential Lorenz curve
fig, ax = plt.subplots(figsize=(6, 5))
ax.plot([0, 1], [0, 1], color=GREY, label="equality")
ax.plot(grid, ref, color=REF, linestyle="--", label="exponential (Gini = 0.5)")
ax.plot(p_, l_, color=PALETTE[0], linewidth=1.8, label="Lorenz curve")
ax.set_xlabel("Share of units, shortest-lived first")
ax.set_ylabel("Share of total lifetime")
ax.set_title(f"Lorenz curve: Gini {gini:.3f}", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads lorenz-gini-demo.csv · app theme from the optional codesplash helper
# Lorenz curve and Gini — Codesplash Chart Lab (recipe "lorenz-gini")
# controls: reference=true
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("lorenz-gini-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")
V = "hours"
x = np.sort(df[V].dropna().to_numpy(dtype=float))
n = x.size
p_ = np.concatenate(([0.0], np.arange(1, n + 1) / n))
l_ = np.concatenate(([0.0], np.cumsum(x) / x.sum()))
gini = 2 * np.sum((2 * np.arange(1, n + 1) - n - 1) * x) / (2 * n * (n - 1) * x.mean())
grid = np.linspace(0, 0.999, 60)
ref = grid + (1 - grid) * np.log1p(-grid) # exponential Lorenz curve
fig = go.Figure()
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color=GREY), name="equality")
fig.add_scatter(x=grid, y=ref, mode="lines", line=dict(color=REF, dash="dash"), name="exponential (Gini = 0.5)")
fig.add_scatter(x=p_, y=l_, mode="lines", line=dict(color=PALETTE[0]), name="Lorenz curve")
fig.update_layout(title=f"Lorenz curve: Gini {gini:.3f}", xaxis_title="Share of units, shortest-lived first", yaxis_title="Share of total lifetime")
fig.show()Needs pandas, numpy, plotly · reads lorenz-gini-demo.csv · app theme from the optional codesplash helper
# Lorenz curve and Gini — Codesplash Chart Lab (recipe "lorenz-gini")
# controls: reference=true
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("lorenz-gini-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
v_col <- "hours"
x <- sort(df[[v_col]][!is.na(df[[v_col]])])
n <- length(x)
curve <- data.frame(p = c(0, seq_len(n) / n), l = c(0, cumsum(x) / sum(x)))
gini <- 2 * sum((2 * seq_len(n) - n - 1) * x) / (2 * n * (n - 1) * mean(x))
grid <- seq(0, 0.999, length.out = 60)
ref <- data.frame(p = grid, l = grid + (1 - grid) * log1p(-grid)) # exponential Lorenz curve
p <- ggplot(curve, aes(p, l)) + geom_abline(slope = 1, intercept = 0, colour = grey_col) +
geom_line(data = ref, colour = ref_col, linetype = "dashed") + geom_line(colour = cs_cat[1], linewidth = 0.8) +
labs(x = "Share of units, shortest-lived first", y = "Share of total lifetime", title = sprintf("Lorenz curve: Gini %.3f", gini)) + theme_cs
print(p)Needs ggplot2 · reads lorenz-gini-demo.csv · app theme from the optional codesplashr helper