Construct cumulative population and amount shares with an equality reference, a declared observation unit and an explicit zero-value policy.
Lorenz curves: audit ranked shares before quoting a Gini value
Fix the population and the quantity
A Lorenz curve ranks units from the smallest nonnegative amount to the largest, then plots cumulative population share against cumulative amount share. The unit might be a household, customer, shipment or location; the amount might be income, support hours or energy consumption. State both. A curve over customers cannot be compared directly with one over invoices when some customers generate many invoices. Start at zero, zero and finish at one, one. The diagonal is an equal-share reference, not a fitted trend. Grain and denominator decisions determine the curve before a single point is drawn. Print the total amount, number of units, observation window and eligibility exclusions beside the chart.
Keep zero values and define negative values
A unit with zero amount still occupies population share. It produces a horizontal segment at the bottom of the curve, often an important feature rather than noise to filter out. Negative amounts break the ordinary nonnegative Lorenz interpretation: debt, net profit and refunds need a separately defined policy, not an unannounced absolute value or shift. Missing amounts are different again. Disclose their count and decide whether the published population excludes them, estimates them, or uses a sensitivity range. If the source is a survey with weights, each unit's horizontal step is its normalized sampling weight; an unweighted curve like the code below must not be labeled as a population-weighted estimate. An empirical CDF ranks values too, but its vertical axis counts units rather than their cumulative share of an amount.
Calculate area on the points actually shown
For nonnegative individual amounts with equal unit weight, the Gini value is one minus twice the area under the piecewise-linear Lorenz curve. Calculate that area from every sorted unit boundary, not from a handful of plotted labels or a smoothed curve. A summary rounded to two decimals can hide a change that matters to policy, so show the underlying curve and selected checkpoints such as the bottom half's amount share. A Gini value near zero means the measured amount is distributed more evenly across the included units. It says nothing by itself about whether total resources are adequate. Uncertainty and support deserve attention when comparing small places or sampled populations.
Compare periods without swapping the denominator
Two curves can cross; then one scalar Gini cannot describe which segment has a larger share at every population depth. Put both periods on identical zero-to-one axes, retain the same unit definition and describe major population or data-collection changes. A rising total can coexist with a more bowed curve, and a falling total with a straighter one. Show totals as a separate companion view rather than asking normalized curves to reveal volume. If a few units dominate the tail, provide a table of their share without exposing private identities. Shared-scale panels and text alternatives keep the comparison readable without relying on line color alone.
Worked contract
from math import isfinite
def lorenz_ledger(amounts: list[tuple[str, float]]):
unit_ids = [unit_id for unit_id, _ in amounts]
if not amounts or len(unit_ids) != len(set(unit_ids)) or any(
not unit_id for unit_id in unit_ids):
raise ValueError("units need unique, nonempty IDs")
if any(not isfinite(amount) or amount < 0 for _, amount in amounts):
raise ValueError("ordinary Lorenz amounts must be finite and nonnegative")
total = sum(amount for _, amount in amounts)
if total <= 0:
raise ValueError("positive total amount is required")
ranked = sorted(amounts, key=lambda record: record[1])
points = [(0.0, 0.0)]
cumulative = 0.0
for position, (_, amount) in enumerate(ranked, start=1):
cumulative += amount
points.append((position / len(ranked), cumulative / total))
doubled_area = sum((points[index][0] - points[index - 1][0]) *
(points[index][1] + points[index - 1][1])
for index in range(1, len(points)))
return points, 1 - doubled_area
district_amounts = [("district-47", 47.0), ("district-59", 59.0),
("district-83", 83.0), ("district-211", 211.0)]
curve, gini = lorenz_ledger(district_amounts)
assert curve[2] == (0.5, 106 / 400)
assert curve[-1] == (1.0, 1.0)
assert abs(gini - 0.3225) < 1e-12
assert lorenz_ledger([("empty-47", 0.0), ("full-59", 47.0)])[0][1] == (0.5, 0.0)Performance and operating cost
For N units, sorting takes O(N log N) time and the cumulative sweep plus trapezoidal area take O(N). The ranked records, uniqueness set and point list need O(N) space. The four-district check yields bottom-half share 0.265 and Gini 0.3225; a separate zero-amount check proves that zero units remain in the population. This code is deliberately unweighted and rejects negative amounts. Survey weights or negative wealth require a different declared calculation and interpretation.
Common Mistakes
- Ranking invoices while describing the horizontal axis as households.
- Removing zero-amount units because they make a flat segment.
- Calculating Gini from smoothed drawing coordinates instead of the ranked data.
- Comparing two normalized curves without reporting totals and population coverage.
Validation drill
Build two yearly curves for 470 synthetic service districts. Reconcile every amount to the published total, include zero-use districts, show bottom-half and top-decile shares, and explain any missing or negative records before comparing Gini values.
