Charts#

Draw the result tables of the other modules with matplotlib, one function per table, such as woe_chart() for a WOE table, roc_chart() for a ROC table and monitoring_chart() for a monitoring report. Each function draws on the Axes passed as ax, or on a new figure, and returns the Axes it drew on. matplotlib is an optional dependency: install it with pip install "kivi[plot]".

See Charts for examples on the bundled data.

woe_chart(table, *[, line, ax])

Draw the population share of each group with its event rate or WOE.

correlation_chart(matrix, *[, ax])

Draw a correlation matrix as a heatmap with the value in each cell.

roc_chart(table, *[, ks, label, ax])

Draw the ROC curve, with the largest gap between the two rates marked.

precision_recall_chart(table, *[, label, ax])

Draw the precision against the recall of every threshold of a score.

gains_chart(table, *[, ks, label, ax])

Draw the cumulative shares of events and non-events by score band.

distribution_chart(table, *[, ax])

Draw the share of all non-events and of all events in each group side by side.

calibration_chart(table, *[, label, ax])

Draw the observed event rate of each group against its mean predicted PD.

cutoff_chart(table, *[, label, ax])

Draw the event rate of the approved book against the approval rate.

psi_chart(table, *[, ax])

Draw the reference and the current share of each group side by side.

monitoring_chart(table, *[, column, kind, ...])

Draw one column of a monitoring report period by period.

vintage_chart(table, *[, ax])

Draw one curve per cohort of its cumulative bad rate by month on book.

kivi.plotting.woe_chart(table, *, line='event_rate', ax=None)#

Draw the population share of each group with its event rate or WOE.

The bars show total_share, the share of the sample in each group, on the left y-axis, and a line shows event_rate or woe on a second y-axis on the right. This is the one chart of the module with two y-axes, and so the one that returns two Axes. The groups keep the order of the table, and the legend gives the IV of the whole table.

Parameters:
tablepandas.DataFrame

A table from kivi.woe.woe_table, or one of the tables of a kivi.spec.BinningSpec. It needs the columns total_share, iv and the column named by line.

line{‘event_rate’, ‘woe’}, default ‘event_rate’

Column drawn as the line.

axmatplotlib.axes.Axes, optional

Axes of the bars. A new figure is created when it is not given.

Returns:
barsmatplotlib.axes.Axes

Axes of the bars, ax when it is given.

linematplotlib.axes.Axes

Axes of the line, a twin of bars that shares its x-axis.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, line is neither 'event_rate' nor 'woe', or ax is not a matplotlib Axes.

See also

kivi.woe.woe_table

The table that this chart draws.

psi_chart

Compare the shares of two samples in the same groups.

Notes

The tick labels are the group labels of the index, with NaN for the group of missing values. Sort the table first, for example with table.sort_index() or table.sort_values("woe"), to draw the groups in another order.

Each y-axis is labeled in the color of what it shows, and the dotted line of zero WOE belongs to the right axis. Both axes leave room at the top for the legend, so that it covers no bar and no point.

Examples

>>> import pandas as pd
>>> from kivi.plotting import woe_chart
>>> from kivi.woe import woe_table
>>> groups = pd.Series(["a", "b", "b", "c", "c", "c"])
>>> target = pd.Series([1, 0, 1, 0, 0, 1])
>>> bars, line = woe_chart(woe_table(groups, target))
>>> [label.get_text() for label in bars.get_xticklabels()]
['a', 'b', 'c']
>>> line.get_ylabel()
'event_rate'
kivi.plotting.correlation_chart(matrix, *, ax=None)#

Draw a correlation matrix as a heatmap with the value in each cell.

Positive correlations are blue and negative ones amber, darker as they approach 1 or -1, so that pairs of variables that carry the same information stand out before a model is fitted.

Parameters:
matrixpandas.DataFrame

Square matrix of correlations with the same labels, in the same order, in its index and columns, such as X.corr() or X.corr(method="spearman") of the WOE-encoded candidates X.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure, sized to the number of variables, is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If matrix is not a DataFrame, has no rows, does not have the same labels in its index and columns, has a column that is not numeric or a value outside [-1, 1], such as a covariance, or ax is not a matplotlib Axes.

See also

kivi.selection.correlation_filter

Drop one variable of each highly correlated pair.

kivi.selection.vif

Variance inflation factor of each variable.

Notes

The colors run from -1 to 1 whatever the values, and a missing value, such as the correlation of a constant column, leaves its cell empty. The heatmap is ax.images[0], so ax.figure.colorbar(ax.images[0], ax=ax) adds a color bar.

Examples

>>> import pandas as pd
>>> from kivi.plotting import correlation_chart
>>> X = pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 1, 4, 3], "c": [4, 3, 2, 1]})
>>> ax = correlation_chart(X.corr())
>>> [label.get_text() for label in ax.get_yticklabels()]
['a', 'b', 'c']
>>> ax.texts[1].get_text()
'0.60'
kivi.plotting.roc_chart(table, *, ks=True, label=None, ax=None)#

Draw the ROC curve, with the largest gap between the two rates marked.

The curve plots true_positive_rate against false_positive_rate from the strictest threshold to the loosest, next to the diagonal of a score that ranks at random. With ks, a vertical segment marks the KS statistic: the largest distance between the curve and the diagonal.

Parameters:
tablepandas.DataFrame

A table from kivi.metrics.roc_table. It needs the columns false_positive_rate and true_positive_rate.

ksbool, default True

Whether to mark the KS statistic.

labelstr, optional

Legend entry of the curve. A legend is drawn only when a curve has a label.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, ks is not True or False, or ax is not a matplotlib Axes.

See also

kivi.metrics.roc_table

The table that this chart draws.

kivi.metrics.roc_auc

Area under the curve.

gains_chart

The same separation against the share of the sample.

Notes

The curve takes the next color of the Axes’ color cycle, so that ROC curves of several scores drawn on the same ax are told apart by color and by label. The KS segment and its value share the color of their curve.

Examples

>>> from kivi.metrics import roc_table
>>> from kivi.plotting import roc_chart
>>> table = roc_table([0.1, 0.4, 0.35, 0.8], [0, 0, 1, 1])
>>> ax = roc_chart(table)
>>> ax.get_xlabel(), ax.get_ylabel()
('false_positive_rate', 'true_positive_rate')
>>> ax.texts[0].get_text()
'ks = 0.500'
kivi.plotting.precision_recall_chart(table, *, label=None, ax=None)#

Draw the precision against the recall of every threshold of a score.

Flagging the observations from the highest score down, the curve plots precision, the event rate of the flagged observations, against true_positive_rate, the share of all events flagged, also called the recall, as steps whose area is the average precision. A dashed line marks the event rate of the sample, the precision of a score that ranks at random.

Parameters:
tablepandas.DataFrame

A table from kivi.metrics.roc_table. It needs the columns true_positive_rate and precision.

labelstr, optional

Legend entry of the curve. A legend is drawn only when a curve has a label.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, no row has a precision, or ax is not a matplotlib Axes.

See also

kivi.metrics.roc_table

The table that this chart draws.

roc_chart

The true positive rate against the false positive rate.

kivi.strategy.confusion_table

Precision and recall at chosen cut-offs.

Notes

The first row of a roc table, at the threshold inf, flags nobody and has no precision. From a recall of 0, the curve steps through the other rows: from the recall of one row to that of the next, it stays at the precision of the next row. Straight lines between the rows would overstate the precision between them [1]. With \(R_n\) and \(P_n\) the recall and the precision of the n-th row, and \(R_0 = 0\), the area under the steps is the average precision

\[\mathrm{AP} = \sum_n (R_n - R_{n-1})\, P_n.\]

The last row flags every observation, so its precision is the event rate: the curve ends on the dashed line, which is labeled with that rate at its left end.

The curve takes the next color of the Axes’ color cycle, so that the curves of several scores drawn on the same ax are told apart by color and by label. The dashed line is gray, as the diagonal of roc_chart, and is drawn once for each event rate shown, so that the scores of one sample share it and two samples get one line each.

References

[1]

J. Davis and M. Goadrich, “The Relationship Between Precision-Recall and ROC Curves”, Proceedings of the 23rd International Conference on Machine Learning, 233-240, 2006.

Examples

>>> from kivi.metrics import roc_table
>>> from kivi.plotting import precision_recall_chart
>>> table = roc_table([0.1, 0.4, 0.35, 0.8], [0, 0, 1, 1])
>>> ax = precision_recall_chart(table)
>>> ax.get_xlabel(), ax.get_ylabel()
('true_positive_rate', 'precision')
>>> ax.texts[0].get_text()
'event_rate = 0.5'
kivi.plotting.gains_chart(table, *, ks=True, label=None, ax=None)#

Draw the cumulative shares of events and non-events by score band.

Reviewing the bands from the highest scores down, the curves show the share of all events and of all non-events captured against the share of the sample reviewed, cum_total_share. With ks, a vertical segment marks the band with the largest ks, the gap between the two curves.

Parameters:
tablepandas.DataFrame

A table from kivi.metrics.gains_table, with the highest band first. It needs the columns cum_total_share, cum_event_share, cum_non_event_share and ks.

ksbool, default True

Whether to mark the largest ks.

labelstr, optional

Name of the score, added to the legend entries of both curves, as in cum_event_share (label).

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, ks is not True or False, or ax is not a matplotlib Axes.

See also

kivi.metrics.gains_table

The table that this chart draws.

roc_chart

The same separation over all thresholds.

Notes

Both curves start at the origin, before the first band is reviewed, and each band adds one point. The diagonal is the cum_event_share of a score that ranks at random.

The cum_event_share curve is solid and the cum_non_event_share curve dashed, both in the next color of the Axes’ color cycle, so that the gains of several scores drawn on the same ax are told apart by color and by label. The KS segment and its value share that color. The legend goes where it covers the fewest points; with several scores it has two entries for each, and ax.legend(loc=...) moves it.

Examples

>>> from kivi.metrics import gains_table
>>> from kivi.plotting import gains_chart
>>> score = [1, 2, 3, 3, 4, 5, 1, 2]
>>> target = [0, 0, 1, 0, 1, 1, 0, 0]
>>> ax = gains_chart(gains_table(score, target, bins=3))
>>> ax.get_xlabel()
'cum_total_share'
>>> ax.texts[0].get_text()
'ks = 0.800'
kivi.plotting.distribution_chart(table, *, ax=None)#

Draw the share of all non-events and of all events in each group side by side.

Each row of the table, such as a score band of a gains table or a bin of a WOE table, gets a pair of bars: its share of all the non-events of the table and its share of all the events, from the raw non_event and event counts. The further apart the two distributions lie, the better the score or the variable tells the classes apart.

Parameters:
tablepandas.DataFrame

A table from kivi.metrics.gains_table or kivi.woe.woe_table, or one of the tables of a kivi.spec.BinningSpec. It needs the columns non_event and event.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, a count is negative or not finite, the table counts no event or no non-event, or ax is not a matplotlib Axes.

See also

kivi.metrics.gains_table

Score bands, with the highest first.

kivi.woe.woe_table

Bins or groups of a variable.

gains_chart

The cumulative shares of the same bands.

psi_chart

The shares of two samples in the same groups.

Notes

The bars keep the order of the table, the highest band first for a gains table, and its empty rows, so that the charts of two samples binned on the same edges line up. The shares are not smoothed, so for a group without events or without non-events they differ from the event_share and non_event_share columns of a WOE table, which give an empty cell the smoothing. The tick labels are the group labels of the index, with NaN for the group of missing values.

The non-events are blue and the events red. The y-axis leaves room at the top for the legend, so that it covers no bar.

Examples

>>> from kivi.metrics import gains_table
>>> from kivi.plotting import distribution_chart
>>> score = [1, 2, 3, 3, 4, 5, 1, 2]
>>> target = [0, 0, 1, 0, 1, 1, 0, 0]
>>> ax = distribution_chart(gains_table(score, target, bins=3))
>>> [label.get_text() for label in ax.get_xticklabels()]
['(3.0, inf]', '(2.0, 3.0]', '(-inf, 2.0]']
>>> [f"{bar.get_height():.2f}" for bar in ax.patches]
['0.00', '0.20', '0.80', '0.67', '0.33', '0.00']
kivi.plotting.calibration_chart(table, *, label=None, ax=None)#

Draw the observed event rate of each group against its mean predicted PD.

Each group of the table, such as a grade or a PD band, is one point with mean_probability on the x-axis and event_rate on the y-axis. Points on the diagonal are calibrated, points above it have more events than predicted and points below it fewer.

Parameters:
tablepandas.DataFrame

A table from kivi.calibration.calibration_table. It needs the columns mean_probability and event_rate.

labelstr, optional

Legend entry of the points. A legend is drawn only when a line has a label.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, or ax is not a matplotlib Axes.

See also

kivi.calibration.calibration_table

The table that this chart draws.

kivi.calibration.binomial_test

Test the default rate of each grade.

Notes

Both axes run from 0 to just above the largest rate drawn on ax, so that the diagonal stays at 45 degrees. The points are joined in the order of the table and take the next color of the Axes’ color cycle, so that the PDs of several models, or the same PDs before and after a correction, can be compared on one ax.

Examples

>>> from kivi.calibration import calibration_table
>>> from kivi.plotting import calibration_chart
>>> grade = ["A", "A", "B", "B", "B", "C"]
>>> target = [0, 0, 0, 1, 0, 1]
>>> probability = [0.05, 0.1, 0.2, 0.3, 0.25, 0.6]
>>> ax = calibration_chart(calibration_table(grade, target, probability))
>>> ax.get_xlabel(), ax.get_ylabel()
('mean_probability', 'event_rate')
kivi.plotting.cutoff_chart(table, *, label=None, ax=None)#

Draw the event rate of the approved book against the approval rate.

Each cut-off of the table is one point, with approval_rate on the x-axis and approved_event_rate, the bad rate of the approved book, on the y-axis. A higher cut-off approves more applicants and lets more events through, so the curve shows the price in risk of each extra point of approval rate.

Parameters:
tablepandas.DataFrame

A table from kivi.strategy.cutoff_table. It needs the columns approval_rate and approved_event_rate.

labelstr, optional

Legend entry of the curve. A legend is drawn only when a curve has a label.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, or ax is not a matplotlib Axes.

See also

kivi.strategy.cutoff_table

The table that this chart draws.

kivi.strategy.swap_set

Compare the decisions of two scores.

Notes

A cut-off below every score approves nothing and has a missing approved_event_rate, so it is left out of the curve. The curve takes the next color of the Axes’ color cycle, so that the curves of a current and a new score can be compared on one ax. The y-axis runs from 0 to just above the largest rate drawn on ax.

Examples

>>> from kivi.plotting import cutoff_chart
>>> from kivi.strategy import cutoff_table
>>> score = [0.1, 0.2, 0.2, 0.3, 0.5, 0.6, 0.8, 0.9]
>>> target = [0, 0, 1, 0, 0, 1, 1, 1]
>>> ax = cutoff_chart(cutoff_table(score, target, cutoffs=[0.2, 0.5, 1.0]))
>>> ax.get_xlabel(), ax.get_ylabel()
('approval_rate', 'approved_event_rate')
kivi.plotting.psi_chart(table, *, ax=None)#

Draw the reference and the current share of each group side by side.

Each group of the table gets a pair of bars, reference_share and current_share, and the legend gives the PSI of the whole table, so that the groups whose shares moved most can be read off directly.

Parameters:
tablepandas.DataFrame

A table from kivi.stability.psi_table. It needs the columns reference_share, current_share and psi.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, lacks a column it needs or has no rows, a column it needs is not numeric, or ax is not a matplotlib Axes.

See also

kivi.stability.psi_table

The table that this chart draws.

monitoring_chart

The PSI of a score in each period.

Notes

The shares are those of the table, so with smoothing a group that is empty in one sample shows the small share that smoothing gave it. The tick labels are the group labels of the index, with NaN for the group of missing values.

The y-axis leaves room at the top for the legend, so that it covers no bar.

Examples

>>> import pandas as pd
>>> from kivi.plotting import psi_chart
>>> from kivi.stability import psi_table
>>> reference = pd.Series(["a", "a", "b", "b", "c", "c"])
>>> current = pd.Series(["a", "b", "b", "c", "c", "c"])
>>> ax = psi_chart(psi_table(reference, current))
>>> ax.get_legend().get_title().get_text()
'psi = 0.183'
kivi.plotting.monitoring_chart(table, *, column='psi', kind='line', label=None, levels=(), ax=None)#

Draw one column of a monitoring report period by period.

The periods of the table run along the x-axis in its order, and column is drawn as a line or as bars, as kind says. Dashed lines can mark the levels that the column is compared with, such as the PSI thresholds or the Gini of the development sample.

Parameters:
tablepandas.DataFrame

A table from kivi.monitoring.monitoring_table, or another table with one row per period, such as one from kivi.monitoring.stability_table. It needs the column named by column.

columnstr, default ‘psi’

Column to draw.

kind{‘line’, ‘bar’}, default ‘line’

Draw the column as a line, which suits rates and measures such as event_rate and gini and several columns on one ax, or as bars, which suit counts such as total and a single psi.

labelstr, optional

Legend entry of the line or the bars. A legend is drawn only when something on the Axes has a label.

levelsfloat or sequence of float, default ()

Values of column to mark with dashed horizontal lines, such as the PSI thresholds [0.1, 0.25] or the Gini of the development sample. Each line is labeled with its value at its right end.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame, has no rows or has no numeric column named column, kind is neither 'line' nor 'bar', a level is not a finite number, or ax is not a matplotlib Axes.

See also

kivi.monitoring.monitoring_table

The table that this chart draws.

psi_chart

The shares behind the PSI of one period.

Notes

The y-axis is labeled with column, or with psi when the columns of table are named variable, as those of kivi.monitoring.stability_table are, whose columns are the PSIs of the variables. The x-axis is labeled with the name of the index.

A missing value, such as the gini of a period whose outcomes are not known yet, leaves a gap in the line and no bar. To draw several columns, call the function once for each: on the panels of one figure for columns on different scales, or on one ax with a label each, as for the variables of a stability table. The line or the bars take the next color of the Axes’ color cycle, and the legend sits to the right of the Axes, so that it covers no line.

Examples

>>> from kivi.monitoring import monitoring_table
>>> from kivi.plotting import monitoring_chart
>>> score = [0.1, 0.3, 0.6, 0.8, 0.2, 0.4, 0.7, 0.9]
>>> period = ["2025-01"] * 4 + ["2025-02"] * 4
>>> target = [0, 0, 1, 1, 0, 1, 0, 1]
>>> report = monitoring_table(score, period, target, reference_period="2025-01", bins=2)
>>> ax = monitoring_chart(report, column="gini", levels=0.5)
>>> [label.get_text() for label in ax.get_xticklabels()]
['2025-01', '2025-02']
>>> ax.get_ylabel()
'gini'
kivi.plotting.vintage_chart(table, *, ax=None)#

Draw one curve per cohort of its cumulative bad rate by month on book.

Each row of the table is a cohort and each column a month on book. Later cohorts are drawn in darker blue, so that a cohort whose curve rises faster than those before it stands out.

Parameters:
tablepandas.DataFrame

A table from kivi.vintage.vintage_table, with one row per cohort and one numeric column per month on book, or another table of the same shape, such as cumulative PDs from kivi.lifetime.convert_pd.

axmatplotlib.axes.Axes, optional

Axes to draw on. A new figure is created when it is not given.

Returns:
matplotlib.axes.Axes

The Axes drawn on, ax when it is given.

Raises:
ImportError

If matplotlib is not installed.

ValueError

If table is not a DataFrame or has no rows, its columns are not numbers, it holds a value that is not numeric, or ax is not a matplotlib Axes.

See also

kivi.vintage.vintage_table

The table that this chart draws.

kivi.lifetime.convert_pd

Turn the curves into marginal or conditional PDs.

Notes

The missing months of a cohort, those it has not reached or that come before its first observed month on book, are left out of its curve. The x-axis is labeled with the name of the columns.

The legend sits to the right of the Axes, so that it covers no curve, and is titled with the name of the index. It names every cohort when there are at most eight, and otherwise eight cohorts evenly spread from the first to the last, since the shades of the others lie between theirs. In a figure of several panels, use a layout engine, such as layout="constrained", to make room for it.

Examples

>>> from kivi.plotting import vintage_chart
>>> from kivi.vintage import vintage_table
>>> loan = [1, 1, 1, 2, 2, 3, 3, 3]
>>> cohort = ["2024-01", "2024-01", "2024-01", "2024-01", "2024-01",
...           "2024-02", "2024-02", "2024-02"]
>>> month_on_book = [1, 2, 3, 1, 2, 1, 2, 3]
>>> bad = [0, 1, 1, 0, 0, 0, 0, 1]
>>> ax = vintage_chart(vintage_table(loan, cohort, month_on_book, bad))
>>> ax.get_xlabel()
'month_on_book'
>>> [text.get_text() for text in ax.get_legend().get_texts()]
['2024-01', '2024-02']