Plotting API
Model Auditor exposes two Matplotlib surfaces and one renderer-independent hierarchy compiler.
Optional dependencies
Section titled “Optional dependencies”Install Matplotlib for the first two APIs:
python -m pip install matplotlibInstall a renderer such as Plotly separately for hierarchy output:
python -m pip install plotlyScoreEvaluation.plot_metric_intervals
Section titled “ScoreEvaluation.plot_metric_intervals”plot_metric_intervals( metric: str, feature_names: list[str] | None = None, include_overall: bool = True, rotate_plots: bool = False, include_sample_size: bool = True, include_class_balance: bool = True,) -> dict[str, tuple[Figure, Axes]]Metric selection
Section titled “Metric selection”Resolution order:
- exact internal metric-name match;
- display-label match across selected features.
An unknown selector raises ValueError listing available names and labels.
Interval feature selection
Section titled “Interval feature selection”None: every result feature except syntheticoverall.- explicit list: validates names and preserves list order.
- explicit
overall: filtered out as a standalone figure. - no remaining non-overall feature:
ValueError.
Plottable levels
Section titled “Plottable levels”A level is plottable when:
scoreis not NaN;intervalis notNone; and- both bounds are not NaN.
Infinite bounds are not explicitly filtered.
A selected feature with no plottable level raises ValueError.
Overall comparator
Section titled “Overall comparator”When enabled and available, overall / Overall is prepended to each feature’s levels. It is skipped when its metric or interval is unavailable.
Orientation
Section titled “Orientation”Default:
metric value on x-axislevels on y-axisWith rotate_plots=True:
levels on x-axismetric value on y-axisAnnotations
Section titled “Annotations”Support extraction checks direct metric keys:
nn_posn_negIt can derive truth-class counts and total N from:
n_tpn_tnn_fpn_fnMissing values produce NA annotation fragments.
Figure size
Section titled “Figure size”Width is fixed at 8 inches. Height is:
max(2.5, number of plotted levels × 0.55)Auditor.plot_score_distributions
Section titled “Auditor.plot_score_distributions”plot_score_distributions( score_name: str, feature_names: list[str] | None = None, bins: int | str = 30, density: bool = True, split_classes: bool = False,) -> dict[str, tuple[Figure, np.ndarray]]Data requirements
Section titled “Data requirements”- internal data exists;
- at least one feature is registered;
- score is registered;
- selected feature and score columns contain at least one jointly non-null row.
An outcome is required only for split_classes=True; metrics are not required.
Distribution feature selection
Section titled “Distribution feature selection”None: every registered feature in registration order.- explicit list: validates names and preserves caller order.
- an explicit empty list performs no feature loop and returns an empty dictionary.
Level order
Section titled “Level order”- categorical: declared order, observed levels only;
- non-categorical: first-appearance order after string conversion.
This non-categorical order intentionally differs from ordinary metric and error evaluation, which use pandas’ default sorted group order.
Histograms
Section titled “Histograms”- one vertical axis per level;
- shared x-axis;
- shared bin edges within the feature;
- bin edges computed from the complete non-null feature slice;
- integer and string bin specifications are type-annotated, while the implementation also forwards precomputed edge arrays to NumPy;
- density or raw counts according to
density; - bottom axis labeled with score label or name;
- figure title combines feature and score labels.
The returned axes are normalized with np.atleast_1d.
With split_classes=True, each level overlays negative and positive truth-class
histograms. The outcome must already be registered, binary, and complete. With
density=True, each nonempty class is normalized separately.
HierarchyPlotter
Section titled “HierarchyPlotter”Import:
from model_auditor.plotting import HierarchyPlotterConstructor
Section titled “Constructor”HierarchyPlotter() -> NoneInitial state:
| Attribute | Initial value |
|---|---|
features |
None |
data |
None |
aggregator |
"median" |
score |
None |
set_data
Section titled “set_data”set_data( data: pd.DataFrame,) -> NoneStores the supplied DataFrame reference. compile() later obtains a copy through its preparation helper.
set_features
Section titled “set_features”set_features( features: Hierarchy | list[str],) -> NoneA list produces one HLevel([HItem(name=...)]) per column.
Any other type raises ValueError.
An empty list or empty Hierarchy does not produce a usable compile tree.
set_aggregator
Section titled “set_aggregator”set_aggregator( method: str | Callable,) -> NoneString methods are forwarded to pandas aggregation on the score Series.
Callable methods receive a DataFrame branch and must return one scalar.
Validation occurs during compile().
set_score
Section titled “set_score”set_score( name: str, label: str | None = None, threshold: ThresholdSpec | None = None,) -> NoneStores an AuditorScore. The threshold is retained but not used by v0.1.16 hierarchy compilation.
compile
Section titled “compile”compile( container: str,) -> PlotterDataRequires features and data.
When a score exists:
- root color is the root aggregate;
- child colors are branch aggregates.
Without a score:
- emits a warning;
- colors are
None.
Returns PlotterData.
Hierarchy schemas
Section titled “Hierarchy schemas”The dataclass signatures below use field(default_factory=...) from dataclasses.
Import:
from model_auditor.plotting.schemas import ( HItem, HLevel, Hierarchy, PlotterData,)PlotterData
Section titled “PlotterData”@dataclassclass PlotterData: labels: list = field(default_factory=list) ids: list = field(default_factory=list) parents: list = field(default_factory=list) values: list = field(default_factory=list) colors: list = field(default_factory=list)add(label, node_id, parent, value, color=None) appends one node to every array.
@dataclassclass HItem: name: str query: str | None = NoneThe query is a pandas expression used as an all-rows branch predicate.
HLevel
Section titled “HLevel”@dataclassclass HLevel: items: list[HItem] = field(default_factory=list)Multiple valid items at one level are concatenated into a temporary composite feature.
Hierarchy
Section titled “Hierarchy”@dataclassclass Hierarchy: levels: list[HLevel] = field(default_factory=list)Levels are traversed from root to leaf.