cleverly.plotting.balance#

cleverly.plotting.balance(source: Any, *, max_covariates: int = 30, page: int | None = None, treatment_label: str | None = None, labels: dict[str, str] | None = None, diagnostic: str | None = None, view: Literal['summary', 'panels'] = 'summary', nodes: Sequence[int] | None = None, title: str | Literal[False] | None = None, subtitle: str | Literal[False] | None = None, xlabel: str | Sequence[str] | None = None, ylabel: str | Sequence[str] | None = None, legend: str | Literal[False] = 'top', figsize: tuple[float, float] | None = None) → Figure[source]#

Plot each covariate’s absolute standardized difference before and after weighting.

Use it to check the treatment model on the covariates you know. Each row is a covariate: the hollow marker is the absolute difference in its mean between the two groups before weighting, in standard deviations, and the filled marker is the same difference after weighting each unit with the fit’s own weights. Weighting has worked on a covariate when the filled marker sits left of the dashed line, at 0.1, the usual threshold for a small difference. Covariates are sorted by their difference before weighting.

The weights and the standard deviation follow the estimand, as covariate_balance() describes: for the ATE, each unit weighted by the inverse of the probability of its own arm, and for the ATT or ATC, the group the effect is among left as it is. With more than two arms and the ATE, each arm is compared with all the others, one panel per arm. A categorical covariate has a row per level. The figure is descriptive: it carries no interval or test.

A fit over time (longitudinal, discrete-time survival or continuous-time survival) draws its BalanceOverTime instead. The summary view has one panel per treatment and comparison, each marker the covariate’s difference averaged over the strata of earlier treatments, with a whisker across the strata after weighting. The panels view draws every stratum’s signed difference as a dot, one panel per treatment time and covariate time.

Parameters:
sourceCovariateBalance, BalanceOverTime or a fitted result

The balance, or a fitted result to compute it from: a point-treatment result with the default estimand, or a longitudinal or survival result.

max_covariatesint, default=30

The most covariates to draw. Every covariate above the threshold after weighting is drawn, then those with the largest difference before or after weighting. With page, the number on each page; the last page may hold fewer.

pageint or None, default=None

The page of covariates to draw, starting at 1. Covariates are ranked, those above the threshold after weighting first, and each page holds max_covariates of them, so every covariate can be drawn on some page; on a fit over time each panel is paged the same way. Every difference and the subtitle still read all covariates, and the notes give the page and the number of pages. When omitted, one figure as described under max_covariates.

treatment_labelstr or None, default=None

Words for the treatment in the subtitle and the panel titles, such as "Offer" (read "Offer = 1 vs Offer = 0"); its column name when omitted.

labelsdict or None, default=None

Words for each covariate, keyed by its name.

diagnostic{“confounding”, “feedback”, “censoring”, “joint”} or None, default=None

Which check of a fit over time to draw; the first the report has when omitted. Point-treatment fits take none.

view{“summary”, “panels”}, default=”summary”

For a fit over time, the averaged markers or one dot per stratum. A continuous-time survival fit has no strata, so it draws the summary view only.

nodessequence of int or None, default=None

For a fit over time, the treatment time points to draw; every one in the summary view, and the last four in the panels view, when omitted.

titlestr, False or None, default=None

The title; a short description of the figure when omitted, and none when False.

subtitlestr, False or None, default=None

The line under the title; the plot’s own, which names the estimate and its headline number, when omitted, and none when False.

xlabelstr, sequence of str or None, default=None

The x-axis label. A string replaces the first labelled panel’s label and the same label wherever it repeats; a sequence gives each labelled panel its own, in reading order.

ylabelstr, sequence of str or None, default=None

The y-axis label, given as for xlabel.

legend{“top”, “right”, “bottom”} or False, default=”top”

Where the key goes: above the axes, right of them, or under the figure; False draws no key.

figsizetuple of float or None, default=None

Width and height in inches of a figure the plot creates.

Returns:
Figure

One panel per contrast, up to three across.

Raises:
CapabilityError

When the fit estimated no treatment mechanism or no weights, or diagnostic names a check the fit omits, such as feedback on a survival fit, or view="panels" is asked of a continuous-time survival fit, which has no strata.

DataError

When the treatment, or a treatment node of a fit over time, is continuous.

ValueError

When max_covariates is less than one, page is not a whole number from 1 to the number of pages or is given with view="panels", diagnostic, view or nodes names something the report does not have, or one of them is given for a point-treatment fit.

See also

cleverly.sensitivity.covariate_balance

The same differences as numbers.

Notes

The figure carries no note text. It does not mark an experimental fit or band, one whose interval has no checked coverage because no registered study covers it or a stated condition applies, such as too few clusters: read notes() on the figure before you publish it. For this plot the notes give the standardized difference and the weights used, and name the covariates not drawn or the page drawn.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> from sklearn.linear_model import LinearRegression, LogisticRegression
>>> from cleverly import ATE, CausalStudy, PointTreatment
>>> from cleverly.datasets import make_linear_ate
>>> from cleverly.plotting import balance
>>> frame, _ = make_linear_ate(n=200, seed=0)
>>> study = CausalStudy(
...     frame,
...     design=PointTreatment(outcome="Y", treatment="A", adjustment=("W1", "W2", "W3", "W4")),
... )
>>> result = study.identify(ATE()).estimate(
...     outcome_learner=LinearRegression(),
...     treatment_learner=LogisticRegression(max_iter=1000),
...     cross_fit=False,
...     random_state=0,
... )
>>> fig = balance(result)
>>> fig.axes[0].get_title(loc="left")
'Covariate balance before and after weighting'
>>> plt.close(fig)