chartaudit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
chartaudit/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """chartaudit - catch misleading charts and misleading summary statistics.
2
+
3
+ * ``check(fig)`` audit a matplotlib figure (lie factor, data-ink ratio, ...)
4
+ * ``check_data(x, y)`` Anscombe checks: does r / the regression line tell the truth?
5
+ * ``lie_factor(ax)`` Tufte's lie factor for the bar series on an Axes
6
+ * ``data_ink_ratio(fig)`` Tufte's data-ink ratio of a rendered figure
7
+ * ``load_anscombe()`` Anscombe's quartet, for teaching and demos
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ._chart import LieFactor, check, data_ink_ratio, lie_factor
13
+ from ._data import check_data, load_anscombe
14
+ from ._report import Issue, Report
15
+ from .exceptions import ChartAuditError
16
+
17
+ __all__ = [
18
+ "ChartAuditError",
19
+ "Issue",
20
+ "LieFactor",
21
+ "Report",
22
+ "check",
23
+ "check_data",
24
+ "data_ink_ratio",
25
+ "lie_factor",
26
+ "load_anscombe",
27
+ ]
28
+
29
+ __version__ = "0.1.0"
chartaudit/_chart.py ADDED
@@ -0,0 +1,354 @@
1
+ """Chart checks for matplotlib figures: lie factor, data-ink ratio and friends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ from matplotlib.artist import Artist
11
+ from matplotlib.axes import Axes
12
+ from matplotlib.collections import PathCollection
13
+ from matplotlib.colors import to_rgba
14
+ from matplotlib.container import BarContainer
15
+ from matplotlib.figure import Figure, SubFigure
16
+ from matplotlib.patches import Wedge
17
+
18
+ from ._data import check_data
19
+ from ._report import Issue, Report
20
+
21
+ _RAINBOW = {"jet", "rainbow", "hsv", "gist_rainbow", "nipy_spectral", "gist_ncar", "prism"}
22
+
23
+
24
+ # ============================================================== lie factor
25
+ @dataclass(frozen=True)
26
+ class LieFactor:
27
+ """Lie factor of one bar series (Tufte, 1983).
28
+
29
+ ``value = visual effect / data effect``, where an *effect* is the relative
30
+ difference between the largest and smallest bar. Tufte's tolerance is
31
+ 0.95 to 1.05; ``inf`` means a bar is drawn with zero length.
32
+ """
33
+
34
+ value: float
35
+ smallest: float
36
+ largest: float
37
+ visual_ratio: float
38
+ data_ratio: float
39
+ axis_range: tuple[float, float]
40
+ orientation: str
41
+
42
+
43
+ def _bar_lie_factor(ax: Axes, container: BarContainer) -> LieFactor | None:
44
+ rects = [p for p in container.patches if p.get_visible()]
45
+ if len(rects) < 2:
46
+ return None
47
+ horizontal = getattr(container, "orientation", None) == "horizontal"
48
+ if horizontal:
49
+ starts = np.array([p.get_x() for p in rects])
50
+ lengths = np.array([p.get_width() for p in rects])
51
+ lo, hi = sorted(ax.get_xlim())
52
+ scale = ax.get_xscale()
53
+ else:
54
+ starts = np.array([p.get_y() for p in rects])
55
+ lengths = np.array([p.get_height() for p in rects])
56
+ lo, hi = sorted(ax.get_ylim())
57
+ scale = ax.get_yscale()
58
+ if scale != "linear":
59
+ return None
60
+ if not np.allclose(starts, starts[0]): # stacked bars: lengths are not totals
61
+ return None
62
+ base = float(starts[0])
63
+ tops = starts + lengths
64
+ sign = np.sign(np.median(tops - 0.0)) or 1.0
65
+ values = (tops * sign) # data values measured from the true zero
66
+ if (values <= 0).any(): # mixed signs: effect sizes are not comparable
67
+ return None
68
+ vis = np.abs(np.clip(tops, lo, hi) - np.clip(base, lo, hi))
69
+ i_small, i_large = int(values.argmin()), int(values.argmax())
70
+ vmin, vmax = float(values[i_small]), float(values[i_large])
71
+ if np.isclose(vmin, vmax):
72
+ return None
73
+ data_effect = (vmax - vmin) / vmin
74
+ lmin, lmax = float(vis[i_small]), float(vis[i_large])
75
+ if lmin <= 0:
76
+ visual_effect = float("inf")
77
+ value = float("inf")
78
+ else:
79
+ visual_effect = (lmax - lmin) / lmin
80
+ value = visual_effect / data_effect
81
+ return LieFactor(
82
+ value=value,
83
+ smallest=vmin * sign,
84
+ largest=vmax * sign,
85
+ visual_ratio=(lmax / lmin) if lmin > 0 else float("inf"),
86
+ data_ratio=vmax / vmin,
87
+ axis_range=(float(lo), float(hi)),
88
+ orientation="horizontal" if horizontal else "vertical",
89
+ )
90
+
91
+
92
+ def lie_factor(ax: Axes) -> float | None:
93
+ """Worst (furthest from 1) lie factor among the bar series on ``ax``.
94
+
95
+ Returns ``None`` if the axes has no bar series a lie factor applies to
96
+ (lines, log axes, stacked bars and mixed-sign bars are skipped).
97
+ """
98
+ found = [lf for c in ax.containers if isinstance(c, BarContainer)
99
+ if (lf := _bar_lie_factor(ax, c)) is not None]
100
+ if not found:
101
+ return None
102
+ return max(found, key=lambda lf: abs(np.log(lf.value)) if np.isfinite(lf.value) and lf.value > 0
103
+ else float("inf")).value
104
+
105
+
106
+ # ========================================================== data-ink ratio
107
+ def _figure_of(obj: Figure | SubFigure | Axes) -> Figure:
108
+ fig = obj.figure if isinstance(obj, Axes) else obj
109
+ while isinstance(fig, SubFigure):
110
+ fig = fig.figure
111
+ return fig # type: ignore[return-value]
112
+
113
+
114
+ def _is_colorbar(ax: Axes) -> bool:
115
+ return getattr(ax, "_colorbar", None) is not None
116
+
117
+
118
+ def _non_data_artists(fig: Figure) -> list[Artist]:
119
+ arts: list[Artist] = []
120
+ for ax in fig.axes:
121
+ if _is_colorbar(ax):
122
+ arts.append(ax)
123
+ continue
124
+ arts += list(ax.spines.values())
125
+ arts += [ax.xaxis, ax.yaxis, ax.patch, ax.title]
126
+ arts += [t for t in (getattr(ax, "_left_title", None), getattr(ax, "_right_title", None)) if t]
127
+ arts += list(ax.texts)
128
+ if (leg := ax.get_legend()) is not None:
129
+ arts.append(leg)
130
+ if getattr(ax, "name", "") == "3d":
131
+ arts += [getattr(ax, "zaxis", None)] if getattr(ax, "zaxis", None) else []
132
+ arts += list(fig.texts) + list(fig.legends)
133
+ if getattr(fig, "_suptitle", None) is not None:
134
+ arts.append(fig._suptitle)
135
+ return [a for a in arts if a is not None]
136
+
137
+
138
+ def _render(fig: Figure, dpi: float) -> np.ndarray:
139
+ from matplotlib.image import imread
140
+
141
+ buf = io.BytesIO()
142
+ fig.savefig(buf, format="png", dpi=dpi, facecolor=fig.get_facecolor())
143
+ buf.seek(0)
144
+ img = imread(buf, format="png") # floats in [0, 1]
145
+ return (img * 255).round().astype(np.uint8)
146
+
147
+
148
+ def _ink(img: np.ndarray, background: np.ndarray) -> float:
149
+ diff = np.abs(img[..., :3].astype(np.int16) - background[:3].astype(np.int16))
150
+ return float(diff.max(axis=-1).sum() / 255.0)
151
+
152
+
153
+ def data_ink_ratio(fig: Figure | Axes, dpi: float = 72) -> float:
154
+ """Tufte's data-ink ratio of a rendered figure, between 0 and 1.
155
+
156
+ The figure is rendered twice: once as is, and once with only the data
157
+ marks (lines, bars, points, images, filled areas) visible. Ink is the
158
+ colour distance of each pixel from the figure background, so a pale
159
+ gridline counts for less than a black one. Axes, ticks, labels,
160
+ gridlines, legends, titles, annotations, colorbars and coloured axes
161
+ backgrounds are all counted as non-data ink.
162
+ """
163
+ fig = _figure_of(fig)
164
+ background = (np.array(to_rgba(fig.get_facecolor())) * 255).round()
165
+ total = _ink(_render(fig, dpi), background)
166
+ if total == 0:
167
+ return float("nan")
168
+ hidden = [(a, a.get_visible()) for a in _non_data_artists(fig)]
169
+ try:
170
+ for a, _ in hidden:
171
+ a.set_visible(False)
172
+ data = _ink(_render(fig, dpi), background)
173
+ finally:
174
+ for a, was in hidden:
175
+ a.set_visible(was)
176
+ return min(1.0, data / total)
177
+
178
+
179
+ def _ink_suggestions(fig: Figure) -> list[str]:
180
+ tips: list[str] = []
181
+ for ax in fig.axes:
182
+ if _is_colorbar(ax):
183
+ continue
184
+ if any(g.get_visible() for g in ax.xaxis.get_gridlines() + ax.yaxis.get_gridlines()):
185
+ tips.append("lighten or remove gridlines")
186
+ if ax.spines["top"].get_visible() and ax.spines["right"].get_visible():
187
+ tips.append("remove the top and right spines")
188
+ face, figface = to_rgba(ax.get_facecolor()), to_rgba(fig.get_facecolor())
189
+ if not np.allclose(face[:3], figface[:3]) and face[3] > 0:
190
+ tips.append("drop the coloured axes background")
191
+ leg = ax.get_legend()
192
+ if leg is not None and leg.get_frame_on():
193
+ tips.append("remove the legend frame (or label lines directly)")
194
+ return list(dict.fromkeys(tips))
195
+
196
+
197
+ # =================================================================== check
198
+ def _axes_of(obj: Figure | SubFigure | Axes) -> list[Axes]:
199
+ if isinstance(obj, Axes):
200
+ return [obj]
201
+ return [ax for ax in obj.get_axes()]
202
+
203
+
204
+ def _has_data(ax: Axes) -> bool:
205
+ return bool(ax.lines or ax.collections or ax.images or
206
+ any(isinstance(c, BarContainer) for c in ax.containers) or
207
+ any(isinstance(p, Wedge) for p in ax.patches))
208
+
209
+
210
+ def check(
211
+ fig: Figure | SubFigure | Axes,
212
+ *,
213
+ data_ink: bool = True,
214
+ scatter_data: bool = True,
215
+ dpi: float = 72,
216
+ ) -> Report:
217
+ """Audit a matplotlib figure (or a single Axes) for misleading design.
218
+
219
+ Checks
220
+ ------
221
+ * ``lie_factor``: bar lengths exaggerate or shrink differences
222
+ (usually a bar chart whose value axis does not start at zero)
223
+ * ``data_ink_ratio``: share of ink that shows data, with tips
224
+ * ``dual_axis``: two y-axes on one plot invite false comparisons
225
+ * ``three_d``: 3D projection distorts lengths and areas
226
+ * ``pie_slices``: pies with many slices are hard to compare
227
+ * ``rainbow_colormap``: perceptually non-uniform colormaps
228
+ * ``missing_axis_label``: an axis with data but no label
229
+ * Anscombe checks on every scatter series (see :func:`check_data`)
230
+
231
+ Parameters
232
+ ----------
233
+ data_ink:
234
+ Compute the data-ink ratio (renders the figure twice).
235
+ scatter_data:
236
+ Run :func:`check_data` on scatter series with at least 4 points.
237
+ dpi:
238
+ Resolution for the data-ink rendering.
239
+ """
240
+ axes = _axes_of(fig)
241
+ figure = _figure_of(fig)
242
+ issues: list[Issue] = []
243
+ metrics: dict[str, Any] = {"axes": 0}
244
+ lie_values: list[float] = []
245
+
246
+ def where(ax: Axes) -> str:
247
+ title = ax.get_title()
248
+ if title:
249
+ return f"'{title}'"
250
+ plot_axes = [a for a in figure.axes if not _is_colorbar(a)]
251
+ return f"axes {plot_axes.index(ax) + 1}" if ax in plot_axes and len(plot_axes) > 1 else "chart"
252
+
253
+ for ax in axes:
254
+ if _is_colorbar(ax):
255
+ continue
256
+ metrics["axes"] += 1
257
+
258
+ # ---------------- lie factor
259
+ for c in ax.containers:
260
+ if not isinstance(c, BarContainer):
261
+ continue
262
+ lf = _bar_lie_factor(ax, c)
263
+ if lf is None:
264
+ continue
265
+ lie_values.append(lf.value)
266
+ axis = "x" if lf.orientation == "horizontal" else "y"
267
+ if not np.isfinite(lf.value):
268
+ issues.append(Issue(
269
+ "error", "lie_factor",
270
+ f"{where(ax)}: the bar for {lf.smallest:g} is invisible because the {axis}-axis "
271
+ f"starts at {lf.axis_range[0]:g}; start bar axes at zero.",
272
+ ))
273
+ elif not 0.95 <= lf.value <= 1.05:
274
+ sev = "error" if (lf.value >= 1.5 or lf.value <= 1 / 1.5) else "warning"
275
+ cause = (f"the {axis}-axis starts at {lf.axis_range[0]:g}, not 0"
276
+ if lf.axis_range[0] > 0 or lf.axis_range[1] < 0
277
+ else f"the {axis}-axis is clipped at {lf.axis_range[1]:g}")
278
+ issues.append(Issue(
279
+ sev, "lie_factor",
280
+ f"{where(ax)}: lie factor {lf.value:.2f}. The largest bar looks "
281
+ f"{lf.visual_ratio:.2f}x the smallest but the data ratio is "
282
+ f"{lf.data_ratio:.2f}x ({lf.largest:g} vs {lf.smallest:g}) because {cause}.",
283
+ ))
284
+
285
+ # ---------------- 3D, pies, colormaps, labels
286
+ if getattr(ax, "name", "") == "3d":
287
+ issues.append(Issue("warning", "three_d",
288
+ f"{where(ax)}: 3D projection distorts lengths and angles; "
289
+ "use a 2D chart unless the third dimension is essential."))
290
+ wedges = [p for p in ax.patches if isinstance(p, Wedge)]
291
+ if len(wedges) > 5:
292
+ issues.append(Issue("warning", "pie_slices",
293
+ f"{where(ax)}: pie with {len(wedges)} slices; angles are hard to "
294
+ "compare beyond ~5, consider a sorted bar chart."))
295
+ for mappable in list(ax.images) + list(ax.collections):
296
+ cmap = getattr(mappable, "get_cmap", lambda: None)()
297
+ name = getattr(cmap, "name", "")
298
+ if name in _RAINBOW and getattr(mappable, "get_array", lambda: None)() is not None:
299
+ issues.append(Issue("warning", "rainbow_colormap",
300
+ f"{where(ax)}: colormap '{name}' is not perceptually uniform "
301
+ "and creates false boundaries; use 'viridis' or 'cividis'."))
302
+ break
303
+ if _has_data(ax) and not wedges and getattr(ax, "name", "") != "3d":
304
+ missing = [a for a, lab in (("x", ax.get_xlabel()), ("y", ax.get_ylabel())) if not lab]
305
+ if "x" in missing and any(
306
+ sib.get_xlabel() for sib in ax.get_shared_x_axes().get_siblings(ax) if sib is not ax
307
+ ):
308
+ missing.remove("x") # shared x axes are usually labelled once
309
+ if "x" in missing and not ax.xaxis.get_visible():
310
+ missing.remove("x") # e.g. the hidden x axis of a twinx()
311
+ if missing:
312
+ issues.append(Issue("info", "missing_axis_label",
313
+ f"{where(ax)}: no {' or '.join(missing)} axis label."))
314
+
315
+ # ---------------- Anscombe checks on scatter data
316
+ if scatter_data:
317
+ for coll in ax.collections:
318
+ if isinstance(coll, PathCollection):
319
+ pts = np.asarray(coll.get_offsets(), dtype=float)
320
+ if pts.ndim == 2 and len(pts) >= 4:
321
+ rep = check_data(pts[:, 0], pts[:, 1])
322
+ prefix = "scatter" if where(ax) == "chart" else f"{where(ax)} scatter"
323
+ for i in rep.issues:
324
+ if i.severity != "info":
325
+ issues.append(Issue(i.severity, i.code, f"{prefix}: {i.message}"))
326
+
327
+ # ---------------- dual axes (twinx / twiny)
328
+ plot_axes = [a for a in axes if not _is_colorbar(a)]
329
+ seen: set[int] = set()
330
+ for i, a in enumerate(plot_axes):
331
+ for b in plot_axes[i + 1:]:
332
+ if id(b) in seen:
333
+ continue
334
+ same_box = np.allclose(a.get_position().bounds, b.get_position().bounds)
335
+ shares = (a.get_shared_x_axes().joined(a, b) or a.get_shared_y_axes().joined(a, b))
336
+ if same_box and shares:
337
+ seen.add(id(b))
338
+ issues.append(Issue("warning", "dual_axis",
339
+ f"{where(a)}: two value axes share one plot; readers compare "
340
+ "heights across unrelated scales. Use two panels or index both series."))
341
+
342
+ metrics["lie_factor"] = (max(lie_values, key=lambda v: abs(np.log(v)) if 0 < v < np.inf
343
+ else float("inf")) if lie_values else None)
344
+ if data_ink:
345
+ ratio = data_ink_ratio(figure, dpi=dpi)
346
+ metrics["data_ink_ratio"] = ratio
347
+ tips = _ink_suggestions(figure)
348
+ if np.isfinite(ratio):
349
+ msg = f"{ratio:.0%} of the ink shows data"
350
+ if tips and ratio < 0.9:
351
+ msg += "; to raise it: " + ", ".join(tips)
352
+ sev = "warning" if ratio < 0.2 else "info"
353
+ issues.append(Issue(sev, "data_ink_ratio", msg + "."))
354
+ return Report("ChartReport", metrics, issues)
chartaudit/_data.py ADDED
@@ -0,0 +1,198 @@
1
+ """Anscombe checks: does a summary statistic tell the whole story?
2
+
3
+ Anscombe's quartet (1973) is four datasets with the same mean, variance,
4
+ correlation and regression line that look completely different when plotted.
5
+ :func:`check_data` looks for the patterns that made them different:
6
+
7
+ * a curved relationship summarised by a straight line (dataset II)
8
+ * a single outlier dragging the correlation (dataset III)
9
+ * a single high-leverage point creating the whole correlation (dataset IV)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Sequence
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+
19
+ from ._report import Issue, Report
20
+
21
+ # Anscombe, F. J. (1973). Graphs in Statistical Analysis. The American Statistician 27(1).
22
+ _X123 = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]
23
+ _ANSCOMBE = {
24
+ "I": (_X123, [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]),
25
+ "II": (_X123, [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]),
26
+ "III": (_X123, [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]),
27
+ "IV": (
28
+ [8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8],
29
+ [6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89],
30
+ ),
31
+ }
32
+
33
+
34
+ def load_anscombe() -> dict[str, tuple[np.ndarray, np.ndarray]]:
35
+ """Return Anscombe's quartet as ``{"I": (x, y), ..., "IV": (x, y)}``."""
36
+ return {k: (np.array(x, float), np.array(y, float)) for k, (x, y) in _ANSCOMBE.items()}
37
+
38
+
39
+ def _pearson(x: np.ndarray, y: np.ndarray) -> float:
40
+ sx, sy = x.std(), y.std()
41
+ if sx == 0 or sy == 0:
42
+ return float("nan")
43
+ return float(((x - x.mean()) * (y - y.mean())).mean() / (sx * sy))
44
+
45
+
46
+ def _ranks(a: np.ndarray) -> np.ndarray:
47
+ """Average ranks (ties share their mean rank), without scipy."""
48
+ order = a.argsort(kind="mergesort")
49
+ ranks = np.empty(len(a), float)
50
+ ranks[order] = np.arange(len(a), dtype=float)
51
+ _, inv, counts = np.unique(a, return_inverse=True, return_counts=True)
52
+ sums = np.bincount(inv, weights=ranks)
53
+ return (sums / counts)[inv]
54
+
55
+
56
+ def _r2(y: np.ndarray, fitted: np.ndarray) -> float:
57
+ ss_tot = ((y - y.mean()) ** 2).sum()
58
+ return float("nan") if ss_tot == 0 else float(1 - ((y - fitted) ** 2).sum() / ss_tot)
59
+
60
+
61
+ def _loo_pearson(x: np.ndarray, y: np.ndarray) -> np.ndarray:
62
+ """Pearson r with each point left out, in O(n) using running sums."""
63
+ n = len(x)
64
+ sx, sy = x.sum() - x, y.sum() - y
65
+ sxx, syy = (x * x).sum() - x * x, (y * y).sum() - y * y
66
+ sxy = (x * y).sum() - x * y
67
+ m = n - 1
68
+ cov = sxy - sx * sy / m
69
+ vx = sxx - sx * sx / m
70
+ vy = syy - sy * sy / m
71
+ with np.errstate(divide="ignore", invalid="ignore"):
72
+ return cov / np.sqrt(vx * vy)
73
+
74
+
75
+ def _fmt(v: Any) -> str:
76
+ return f"{v:g}" if isinstance(v, (int, float, np.floating)) else str(v)
77
+
78
+
79
+ def check_data(
80
+ x: Sequence[float] | np.ndarray,
81
+ y: Sequence[float] | np.ndarray,
82
+ *,
83
+ label: str | None = None,
84
+ influence_threshold: float = 0.1,
85
+ curvature_threshold: float = 0.1,
86
+ leverage_threshold: float = 0.5,
87
+ ) -> Report:
88
+ """Check whether the usual summary of ``y`` vs ``x`` hides something.
89
+
90
+ Parameters
91
+ ----------
92
+ x, y:
93
+ Paired numeric observations. Pairs with a missing value are dropped.
94
+ label:
95
+ Optional name used in the report title.
96
+ influence_threshold:
97
+ Flag an outlier if removing it changes Pearson's r by more than this.
98
+ curvature_threshold:
99
+ Flag curvature if a quadratic fit explains this much more variance
100
+ (R squared) than the straight line.
101
+ leverage_threshold:
102
+ Flag a point whose regression leverage exceeds this (1.0 means the
103
+ line is forced through that single point).
104
+
105
+ Returns
106
+ -------
107
+ Report
108
+ ``metrics`` holds n, means, standard deviations, Pearson r,
109
+ Spearman rho, slope, intercept and both R squared values.
110
+ """
111
+ xa = np.asarray(x, dtype=float).ravel()
112
+ ya = np.asarray(y, dtype=float).ravel()
113
+ if xa.shape != ya.shape:
114
+ raise ValueError(f"x and y must have the same length, got {len(xa)} and {len(ya)}.")
115
+ keep = np.isfinite(xa) & np.isfinite(ya)
116
+ dropped = int((~keep).sum())
117
+ xa, ya = xa[keep], ya[keep]
118
+ n = len(xa)
119
+ title = "DataReport" + (f" {label}" if label else "")
120
+ issues: list[Issue] = []
121
+ if dropped:
122
+ issues.append(Issue("info", "missing_values", f"dropped {dropped} pair(s) with NaN/inf."))
123
+ if n < 4:
124
+ issues.append(Issue("info", "too_few_points", f"only {n} point(s); checks skipped."))
125
+ return Report(title, {"n": n}, issues)
126
+
127
+ r = _pearson(xa, ya)
128
+ rho = _pearson(_ranks(xa), _ranks(ya))
129
+ sxx = ((xa - xa.mean()) ** 2).sum()
130
+ if sxx > 0:
131
+ slope = float(((xa - xa.mean()) * (ya - ya.mean())).sum() / sxx)
132
+ intercept = float(ya.mean() - slope * xa.mean())
133
+ lin_r2 = _r2(ya, intercept + slope * xa)
134
+ else:
135
+ slope = intercept = lin_r2 = float("nan")
136
+
137
+ metrics: dict[str, Any] = {
138
+ "n": n,
139
+ "mean_x": float(xa.mean()), "mean_y": float(ya.mean()),
140
+ "sd_x": float(xa.std(ddof=1)), "sd_y": float(ya.std(ddof=1)),
141
+ "pearson_r": r, "spearman_rho": rho,
142
+ "slope": slope, "intercept": intercept,
143
+ "r2_linear": lin_r2, "r2_quadratic": None,
144
+ }
145
+
146
+ n_unique_x = len(np.unique(xa))
147
+ if sxx == 0:
148
+ issues.append(Issue("warning", "constant_x", "x never varies; no relationship can be estimated."))
149
+ return Report(title, metrics, issues)
150
+
151
+ # ---- dataset IV: one point creates the whole relationship -------------
152
+ leverage = 1.0 / n + (xa - xa.mean()) ** 2 / sxx
153
+ i_lev = int(leverage.argmax())
154
+ if leverage[i_lev] > leverage_threshold:
155
+ issues.append(Issue(
156
+ "warning", "high_leverage",
157
+ f"the point (x={_fmt(xa[i_lev])}, y={_fmt(ya[i_lev])}) has leverage "
158
+ f"{leverage[i_lev]:.2f}: the regression line is essentially forced through it"
159
+ + (f"; x takes only {n_unique_x} distinct values" if n_unique_x <= 3 else "")
160
+ + ". Plot the data before trusting r.",
161
+ ))
162
+
163
+ # ---- dataset III: one outlier drags the correlation ------------------
164
+ loo = _loo_pearson(xa, ya)
165
+ delta = np.abs(loo - r)
166
+ delta[~np.isfinite(delta)] = 0.0
167
+ i_inf = int(delta.argmax())
168
+ resid = ya - (intercept + slope * xa)
169
+ mad = np.median(np.abs(resid - np.median(resid)))
170
+ robust_z = np.abs(resid - np.median(resid)) / (1.4826 * mad) if mad > 0 else np.zeros(n)
171
+ already_flagged = i_inf == i_lev and leverage[i_lev] > leverage_threshold
172
+ if delta[i_inf] > influence_threshold and not already_flagged:
173
+ if robust_z[i_inf] > 3.5 or delta[i_inf] > 2 * influence_threshold:
174
+ issues.append(Issue(
175
+ "warning", "influential_outlier",
176
+ f"removing the point (x={_fmt(xa[i_inf])}, y={_fmt(ya[i_inf])}) changes "
177
+ f"Pearson's r from {r:.3f} to {loo[i_inf]:.3f}. One point is shaping the summary.",
178
+ ))
179
+
180
+ # ---- dataset II: a curve summarised by a line ------------------------
181
+ if n_unique_x >= 3 and n >= 5:
182
+ coeffs = np.polyfit(xa, ya, 2)
183
+ quad_r2 = _r2(ya, np.polyval(coeffs, xa))
184
+ metrics["r2_quadratic"] = quad_r2
185
+ if np.isfinite(quad_r2) and quad_r2 - lin_r2 > curvature_threshold:
186
+ issues.append(Issue(
187
+ "warning", "nonlinear",
188
+ f"a curve fits much better than a straight line (R^2 {lin_r2:.2f} -> "
189
+ f"{quad_r2:.2f}); Pearson's r = {r:.3f} describes the wrong shape.",
190
+ ))
191
+
192
+ if np.isfinite(r) and np.isfinite(rho) and abs(r - rho) > 0.25:
193
+ issues.append(Issue(
194
+ "info", "pearson_spearman_gap",
195
+ f"Pearson r = {r:.3f} but Spearman rho = {rho:.3f}; the linear and rank "
196
+ "correlations disagree, so look at the scatter plot.",
197
+ ))
198
+ return Report(title, metrics, issues)
chartaudit/_report.py ADDED
@@ -0,0 +1,121 @@
1
+ """Report objects shared by chart and data checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Literal
8
+
9
+ Severity = Literal["error", "warning", "info"]
10
+
11
+ _ORDER = {"error": 0, "warning": 1, "info": 2}
12
+ _LABEL = {"error": "[ERROR]", "warning": "[WARN ]", "info": "[INFO ]"}
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Issue:
17
+ """One finding.
18
+
19
+ ``severity`` is ``"error"`` (the chart or statistic misleads),
20
+ ``"warning"`` (likely to mislead) or ``"info"`` (worth knowing).
21
+ ``code`` is a stable identifier such as ``"lie_factor"``.
22
+ """
23
+
24
+ severity: Severity
25
+ code: str
26
+ message: str
27
+
28
+ def __str__(self) -> str:
29
+ return f"{_LABEL[self.severity]} {self.code}: {self.message}"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Report:
34
+ """Result of :func:`chartaudit.check` or :func:`chartaudit.check_data`."""
35
+
36
+ kind: str
37
+ metrics: dict[str, Any] = field(default_factory=dict)
38
+ issues: list[Issue] = field(default_factory=list)
39
+
40
+ @property
41
+ def ok(self) -> bool:
42
+ """True when there are no error-level issues."""
43
+ return not self.errors
44
+
45
+ @property
46
+ def errors(self) -> list[Issue]:
47
+ return [i for i in self.issues if i.severity == "error"]
48
+
49
+ @property
50
+ def warnings(self) -> list[Issue]:
51
+ return [i for i in self.issues if i.severity == "warning"]
52
+
53
+ def has_issue(self, code: str) -> bool:
54
+ return any(i.code == code for i in self.issues)
55
+
56
+ def raise_for_issues(self, strict: bool = False) -> Report:
57
+ """Raise :class:`ChartAuditError` on errors (and warnings if ``strict``)."""
58
+ from .exceptions import ChartAuditError
59
+
60
+ failing = self.errors + (self.warnings if strict else [])
61
+ if failing:
62
+ raise ChartAuditError(self, failing)
63
+ return self
64
+
65
+ # ------------------------------------------------------------ rendering
66
+ def _metric_lines(self) -> list[tuple[str, str]]:
67
+ out = []
68
+ for k, v in self.metrics.items():
69
+ if isinstance(v, float):
70
+ v = f"{v:.3f}"
71
+ elif v is None:
72
+ v = "n/a"
73
+ out.append((k, str(v)))
74
+ return out
75
+
76
+ def summary(self) -> str:
77
+ lines = [f"{self.kind}", "-" * 60]
78
+ rows = self._metric_lines()
79
+ if rows:
80
+ w = max(len(k) for k, _ in rows)
81
+ lines += [f"{k:<{w}} {v}" for k, v in rows]
82
+ lines.append("")
83
+ if self.issues:
84
+ lines.append("Issues")
85
+ lines += [f" {i}" for i in sorted(self.issues, key=lambda i: _ORDER[i.severity])]
86
+ else:
87
+ lines.append("No issues found.")
88
+ return "\n".join(lines)
89
+
90
+ __str__ = summary
91
+
92
+ def __repr__(self) -> str:
93
+ return self.summary()
94
+
95
+ def _repr_html_(self) -> str:
96
+ esc = html.escape
97
+ colors = {"error": "#c0392b", "warning": "#b9770e", "info": "#5d6d7e"}
98
+ rows = "".join(
99
+ f"<tr><th style='text-align:left'>{esc(k)}</th><td>{esc(v)}</td></tr>"
100
+ for k, v in self._metric_lines()
101
+ )
102
+ issues = "".join(
103
+ f"<li><b style='color:{colors[i.severity]}'>{i.severity.upper()}</b> "
104
+ f"<code>{esc(i.code)}</code> {esc(i.message)}</li>"
105
+ for i in sorted(self.issues, key=lambda i: _ORDER[i.severity])
106
+ ) or "<li>No issues found.</li>"
107
+ return (
108
+ f"<div class='chartaudit-report'><p><b>{esc(self.kind)}</b></p>"
109
+ f"<table>{rows}</table><ul>{issues}</ul></div>"
110
+ )
111
+
112
+ def to_dict(self) -> dict[str, Any]:
113
+ return {
114
+ "kind": self.kind,
115
+ "metrics": dict(self.metrics),
116
+ "issues": [
117
+ {"severity": i.severity, "code": i.code, "message": i.message}
118
+ for i in self.issues
119
+ ],
120
+ "ok": self.ok,
121
+ }
@@ -0,0 +1,22 @@
1
+ """Exceptions raised by chartaudit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from ._report import Issue, Report
9
+
10
+
11
+ class ChartAuditError(AssertionError):
12
+ """Raised by ``Report.raise_for_issues()``; handy inside tests and CI.
13
+
14
+ The full report is available as ``.report``.
15
+ """
16
+
17
+ def __init__(self, report: Report, issues: list[Issue]):
18
+ self.report = report
19
+ self.issues = issues
20
+ lines = [f"Chart audit failed with {len(issues)} issue(s):"]
21
+ lines += [f" {i}" for i in issues]
22
+ super().__init__("\n".join(lines))
chartaudit/py.typed ADDED
File without changes
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.5
2
+ Name: chartaudit
3
+ Version: 0.1.0
4
+ Summary: Catch misleading charts and misleading statistics: Tufte's lie factor and data-ink ratio for matplotlib, plus Anscombe-style checks on your data.
5
+ Project-URL: Homepage, https://github.com/AnmolAdhikari/chartaudit
6
+ Project-URL: Issues, https://github.com/AnmolAdhikari/chartaudit/issues
7
+ Project-URL: Changelog, https://github.com/AnmolAdhikari/chartaudit/blob/main/CHANGELOG.md
8
+ Author-email: Anmol Adhikari <anmoladhikari03@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: anscombe,chart-linter,data-ink-ratio,data-literacy,data-visualization,lie-factor,matplotlib,statistics,tufte
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Matplotlib
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Education
25
+ Classifier: Topic :: Scientific/Engineering :: Visualization
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Requires-Dist: matplotlib>=3.7
29
+ Requires-Dist: numpy>=1.23
30
+ Provides-Extra: dev
31
+ Requires-Dist: build; extra == 'dev'
32
+ Requires-Dist: pytest>=7; extra == 'dev'
33
+ Requires-Dist: ruff; extra == 'dev'
34
+ Requires-Dist: twine; extra == 'dev'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # chartaudit
38
+
39
+ **Catch misleading charts and misleading statistics before your audience does.**
40
+
41
+ `chartaudit` turns three classic ideas from statistics and visualization research into automatic checks:
42
+
43
+ - **Tufte's lie factor:** does the chart exaggerate the difference in the data?
44
+ - **Tufte's data-ink ratio:** how much of the ink actually shows data?
45
+ - **Anscombe's quartet:** does your correlation or regression line hide a curve, an outlier, or a single point doing all the work?
46
+
47
+ ```bash
48
+ pip install chartaudit
49
+ ```
50
+
51
+ ![A truncated bar chart with lie factor 32.7 next to an honest version with lie factor 1.0](https://raw.githubusercontent.com/AnmolAdhikari/chartaudit/main/docs/lie_factor_example.svg)
52
+
53
+ ## Check a chart
54
+
55
+ ```python
56
+ import matplotlib.pyplot as plt
57
+ import chartaudit
58
+
59
+ fig, ax = plt.subplots()
60
+ ax.bar(["Us", "Them"], [98, 102])
61
+ ax.set_ylim(95, 104)
62
+ ax.set_title("Customer satisfaction")
63
+
64
+ chartaudit.check(fig)
65
+ ```
66
+
67
+ ```
68
+ ChartReport
69
+ ------------------------------------------------------------
70
+ axes 1
71
+ lie_factor 32.667
72
+ data_ink_ratio 0.955
73
+
74
+ Issues
75
+ [ERROR] lie_factor: 'Customer satisfaction': lie factor 32.67. The largest bar looks 2.33x the smallest but the data ratio is 1.04x (102 vs 98) because the y-axis starts at 95, not 0.
76
+ [INFO ] missing_axis_label: 'Customer satisfaction': no x or y axis label.
77
+ [INFO ] data_ink_ratio: 96% of the ink shows data.
78
+ ```
79
+
80
+ A 4% difference drawn as a 133% difference: the chart exaggerates the effect **32.7 times**. Tufte's tolerance is 0.95 to 1.05.
81
+
82
+ ## Check your data (Anscombe's lesson, automated)
83
+
84
+ All four datasets in Anscombe's quartet share the same means, variances, correlation (r = 0.816) and regression line, yet they look completely different. `check_data` finds out which one you have:
85
+
86
+ ```python
87
+ x, y = chartaudit.load_anscombe()["III"]
88
+ chartaudit.check_data(x, y)
89
+ ```
90
+
91
+ ```
92
+ DataReport
93
+ ------------------------------------------------------------
94
+ n 11
95
+ mean_x 9.000
96
+ mean_y 7.500
97
+ sd_x 3.317
98
+ sd_y 2.030
99
+ pearson_r 0.816
100
+ spearman_rho 0.991
101
+ slope 0.500
102
+ intercept 3.002
103
+ r2_linear 0.666
104
+ r2_quadratic 0.685
105
+
106
+ Issues
107
+ [WARN ] influential_outlier: removing the point (x=13, y=12.74) changes Pearson's r from 0.816 to 1.000. One point is shaping the summary.
108
+ ```
109
+
110
+ | Anscombe dataset | What `check_data` reports |
111
+ |---|---|
112
+ | I | no issues: the summary is fair |
113
+ | II | `nonlinear`: a curve fits far better (R² 0.67 → 1.00) |
114
+ | III | `influential_outlier`: one point moves r from 0.816 to 1.000 |
115
+ | IV | `high_leverage`: the whole correlation comes from the point at x = 19 |
116
+
117
+ `check(fig)` runs these data checks automatically on every scatter plot in your figure.
118
+
119
+ ## What gets checked
120
+
121
+ | Code | Severity | Meaning |
122
+ |---|---|---|
123
+ | `lie_factor` | error / warning | bar lengths exaggerate or shrink differences (truncated or clipped value axis) |
124
+ | `data_ink_ratio` | info / warning | share of ink that shows data, with concrete tips to raise it |
125
+ | `dual_axis` | warning | two y-axes on one plot (`twinx`) invite comparisons across unrelated scales |
126
+ | `three_d` | warning | 3D projection distorts lengths and angles |
127
+ | `pie_slices` | warning | a pie with more than 5 slices |
128
+ | `rainbow_colormap` | warning | `jet`, `rainbow` and similar colormaps create false boundaries |
129
+ | `missing_axis_label` | info | an axis with data but no label |
130
+ | `nonlinear` | warning | a straight-line summary of a curved relationship |
131
+ | `influential_outlier` | warning | one point changes Pearson's r by more than 0.1 |
132
+ | `high_leverage` | warning | the regression line is forced through a single point |
133
+
134
+ ## Use it in tests or CI
135
+
136
+ ```python
137
+ def test_report_charts_are_honest():
138
+ fig = make_quarterly_chart()
139
+ chartaudit.check(fig).raise_for_issues() # fails on errors
140
+ chartaudit.check(fig).raise_for_issues(strict=True) # fails on warnings too
141
+ ```
142
+
143
+ Reports also render as a table in Jupyter and export with `report.to_dict()`.
144
+
145
+ ## How it works
146
+
147
+ - **Lie factor** is `visual effect / data effect` (Tufte, 1983), where an effect is the relative difference between the smallest and largest bar. The visual size of each bar is computed from the axis limits, so truncated and clipped axes are measured exactly. Stacked, mixed-sign and log-scale bars are skipped, because the formula does not apply to them.
148
+ - **Data-ink ratio** renders the figure twice, once as is and once with only the data marks, and compares the ink (each pixel's colour distance from the background). Axes, ticks, gridlines, labels, legends, titles, colorbars and coloured backgrounds count as non-data ink.
149
+ - **Anscombe checks** compare linear and quadratic fits, compute leave-one-out correlations (in O(n)) and regression leverage, using NumPy only.
150
+
151
+ ## References
152
+
153
+ - Anscombe, F. J. (1973). Graphs in Statistical Analysis. *The American Statistician*, 27(1), 17–21.
154
+ - Tufte, E. R. (1983). *The Visual Display of Quantitative Information*. Graphics Press.
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ pip install -e ".[dev]"
160
+ pytest
161
+ ```
162
+
163
+ ## License
164
+
165
+ MIT
@@ -0,0 +1,10 @@
1
+ chartaudit/__init__.py,sha256=HlpdBumx4HjGOw_OZ6k70IhQEkFCbZHFXyquM1FR0mI,892
2
+ chartaudit/_chart.py,sha256=Ajtg3Tpo3_O3b-rIOA2cmSIumjSxB2uUTzJcHdrZma0,14872
3
+ chartaudit/_data.py,sha256=M2nBtA2vdmHRfd84VMJvT_qV8VWoe0CCotKWB44us1s,7946
4
+ chartaudit/_report.py,sha256=z0FLCwW_1yuSr--XabKZr1AXJ5DM1YXwFZDuNF3PzpY,3869
5
+ chartaudit/exceptions.py,sha256=UBLYvgRbmkoYX-llYTP5eNAtpNqkqUiZ8u4oWm6CvmA,617
6
+ chartaudit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ chartaudit-0.1.0.dist-info/METADATA,sha256=Ul4pYtnCSUE6UA4cu7pMOXd8U0_xNnT7DquM0Txqu2o,6705
8
+ chartaudit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ chartaudit-0.1.0.dist-info/licenses/LICENSE,sha256=1Q0-Y7BvRDpYJ9oKoih3tKSZmfcfTsS2LP8PdRhIb2w,1071
10
+ chartaudit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anmol Adhikari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.