diff --git a/CHANGELOG.md b/CHANGELOG.md index 60ebd4b..ede4c9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,9 @@ to [Semantic Versioning](https://semver.org/). - `scorecard` reserves room for every line of a column unit, so a unit with a second line (an uncertainty, say) no longer overlaps the heading above it. +- `scorecard` fits column-group titles and units to their own span, as it already did headings: + each wraps at spaces and shrinks until its neighbours clear, so single-column groups with long + titles and long units under adjacent columns no longer overprint each other. ### Notes diff --git a/src/nicefigs/_scorecard.py b/src/nicefigs/_scorecard.py index 69eed7d..7472234 100644 --- a/src/nicefigs/_scorecard.py +++ b/src/nicefigs/_scorecard.py @@ -59,41 +59,79 @@ def wrap_heading(label: str, size: float, width_pt: float) -> str: return "\n".join(lines) -def fit_headings( +def fit_labels( labels: Sequence[str], - lefts: np.ndarray, + spans: Sequence[tuple[float, float]], cell_pt: float, size: float, floor: float, clearance_pt: float = 2.0, ) -> tuple[float, list[str]]: - """The largest heading size, from ``size`` down to ``floor``, at which neighbouring headings clear. + """The largest size, from ``size`` down to ``floor``, at which neighbouring labels clear. - Each label is wrapped to its cell first; a word wider than the cell cannot wrap, so the size - shrinks in 0.1 pt steps until every pair of neighbouring headings is ``clearance_pt`` apart. + Each label is centred on its span (``(start, end)`` in cells) and wrapped to the span's width + first; a word wider than the span cannot wrap, so the size shrinks in 0.1 pt steps until every + pair of neighbouring labels is ``clearance_pt`` apart. Empty labels take no room. Returns: - The size in points and the wrapped headings at that size (at ``floor`` if none clears). + The size in points and the wrapped labels at that size (at ``floor`` if none clears). """ + centres = np.array([0.5 * (a + b) for a, b in spans], dtype=float) + widths = [b - a for a, b in spans] steps = max(int(round((size - floor) / 0.1)), 0) for k in range(steps + 1): f = size - 0.1 * k - heads = [wrap_heading(h, f, cell_pt * 1.04) for h in labels] - half = [0.5 * max(text_width_pt(line, f) for line in h.split("\n")) for h in heads] - pitch = np.diff(np.asarray(lefts, dtype=float)) * cell_pt + wrapped = [wrap_heading(lab, f, w * cell_pt * 1.04) for lab, w in zip(labels, widths)] + half = [0.5 * max(text_width_pt(line, f) for line in h.split("\n")) for h in wrapped] + pitch = np.diff(centres) * cell_pt if all(p - half[j] - half[j + 1] >= clearance_pt for j, p in enumerate(pitch)): - return f, heads - return floor, heads + return f, wrapped + return floor, wrapped + + +def fit_headings( + labels: Sequence[str], + lefts: np.ndarray, + cell_pt: float, + size: float, + floor: float, + clearance_pt: float = 2.0, +) -> tuple[float, list[str]]: + """:func:`fit_labels` for one label per cell starting at ``lefts``.""" + return fit_labels(labels, [(x, x + 1.0) for x in lefts], cell_pt, size, floor, clearance_pt) + + +def group_blocks(groups: Sequence[str], lefts: np.ndarray) -> list[tuple[str, float, float]]: + """``(name, start, end)`` of each run of equal consecutive group names, in cells.""" + blocks = [] + j = 0 + while j < len(groups): + k = j + while k + 1 < len(groups) and groups[k + 1] == groups[j]: + k += 1 + blocks.append((groups[j], float(lefts[j]), float(lefts[k] + 1))) + j = k + 1 + return blocks def header_heights( - headings: Sequence[str], unit_lines: int, has_groups: bool, scale: float, head_size: float | None = None + headings: Sequence[str], + unit_lines: int, + has_groups: bool, + scale: float, + head_size: float | None = None, + *, + unit_size: float | None = None, + group_lines: int = 1, + group_size: float | None = None, ) -> dict[str, float]: """Vertical positions (pt above the top of the grid) of the stacked header elements. ``unit_lines`` is the most lines any column's unit spans (0 without units), so a unit with a - second line, such as an uncertainty, keeps clear of the heading above it. ``head_size`` is the - heading size in points (default ``FS_HEAD * scale``). + second line, such as an uncertainty, keeps clear of the heading above it. ``head_size``, + ``unit_size`` and ``group_size`` are the sizes in points of headings, units and group titles + (default ``FS_HEAD``, ``FS_UNIT`` and ``FS_GROUP`` times ``scale``); ``group_lines`` is the most + lines a group title spans. Returns: ``units`` and ``heading`` (bottoms of those texts), ``rule`` and ``group`` (the group rule @@ -101,14 +139,16 @@ def header_heights( """ n_lines = max((h.count("\n") + 1 for h in headings), default=1) head_size = FS_HEAD * scale if head_size is None else head_size + unit_size = FS_UNIT * scale if unit_size is None else unit_size + group_size = FS_GROUP * scale if group_size is None else group_size units = 3.0 * scale - heading = units + (unit_lines * FS_UNIT * _LINE * scale + 1.0 * scale if unit_lines else 0.0) + heading = units + (unit_lines * unit_size * _LINE + 1.0 * scale if unit_lines else 0.0) top = heading + n_lines * head_size * _LINE * 0.95 + 1.0 * scale rule = group = top if has_groups: rule = top + 3.0 * scale group = rule + 2.5 * scale - top = group + FS_GROUP * _LINE * scale + top = group + group_lines * group_size * _LINE return {"units": units, "heading": heading, "rule": rule, "group": group, "top": top} @@ -124,9 +164,18 @@ def draw_header( cell_pt: float, scale: float, head_size: float | None = None, + unit_size: float | None = None, + group_titles: Sequence[str] | None = None, + group_size: float | None = None, ) -> None: - """Draw column headings (at ``head_size`` pt, default ``FS_HEAD * scale``), units, group titles and rules.""" + """Draw column headings, units, group titles and rules. + + Sizes default to ``FS_HEAD``, ``FS_UNIT`` and ``FS_GROUP`` times ``scale``; ``group_titles`` + holds one (wrapped) title per run of equal ``groups``, the names themselves by default. + """ head_size = FS_HEAD * scale if head_size is None else head_size + unit_size = FS_UNIT * scale if unit_size is None else unit_size + group_size = FS_GROUP * scale if group_size is None else group_size for x, head, unit in zip(lefts, headings, units): if unit: ax.annotate( @@ -136,7 +185,7 @@ def draw_header( textcoords="offset points", ha="center", va="bottom", - fontsize=FS_UNIT * scale, + fontsize=unit_size, color=MUTED, annotation_clip=False, ) @@ -155,24 +204,22 @@ def draw_header( if groups is None: return shift = ScaledTranslation(0, heights["rule"] / 72.0, ax.figure.dpi_scale_trans) - j = 0 - while j < len(groups): - k = j - while k + 1 < len(groups) and groups[k + 1] == groups[j]: - k += 1 - centre = 0.5 * (lefts[j] + lefts[k] + 1) - half = max( - 0.5 * (lefts[k] + 1 - lefts[j]) - 0.04, 0.5 * text_width_pt(groups[j], FS_GROUP * scale) / cell_pt - ) + blocks = group_blocks(groups, lefts) + titles = [name for name, _, _ in blocks] if group_titles is None else list(group_titles) + for (_, start, end), title in zip(blocks, titles): + centre = 0.5 * (start + end) + title_w = max(text_width_pt(line, group_size) for line in title.split("\n")) + half = max(0.5 * (end - start) - 0.04, 0.5 * title_w / cell_pt) ax.annotate( - groups[j], + title, (centre, 0), xytext=(0, heights["group"]), textcoords="offset points", ha="center", va="bottom", - fontsize=FS_GROUP * scale, + fontsize=group_size, color=INK, + linespacing=0.95, annotation_clip=False, ) if group_rule: @@ -187,7 +234,6 @@ def draw_header( clip_on=False, ) ) - j = k + 1 def draw_colorbar( diff --git a/src/nicefigs/tables.py b/src/nicefigs/tables.py index ae399c4..fa39651 100644 --- a/src/nicefigs/tables.py +++ b/src/nicefigs/tables.py @@ -12,6 +12,7 @@ from ._scorecard import ( FS_CBAR, FS_CBAR_TICK, + FS_GROUP, FS_HEAD, FS_ROW, FS_UNIT, @@ -20,6 +21,8 @@ draw_colorbar, draw_header, fit_headings, + fit_labels, + group_blocks, header_heights, text_width_pt, ) @@ -389,8 +392,28 @@ def scorecard( s = font_scale heads_raw = [str(c) for c in col_labels] - units = [prettify_unit((col_units or {}).get(c)) for c in col_labels] - unit_lines = max((u.count("\n") + 1 for u in units if u), default=0) + units_raw = [prettify_unit((col_units or {}).get(c)) for c in col_labels] + blocks = group_blocks(col_groups, lefts) if col_groups is not None else [] + + def _fit_header(cell_pt: float): + """Headings, units and group titles wrapped and sized to clear their neighbours, and their heights.""" + fh, heads = fit_headings(heads_raw, lefts, cell_pt, FS_HEAD * s, FS_UNIT * s) + fu, units = fit_labels(units_raw, [(x, x + 1.0) for x in lefts], cell_pt, FS_UNIT * s, 4.5 * s) + fg, titles = fit_labels( + [b[0] for b in blocks], [b[1:] for b in blocks], cell_pt, FS_GROUP * s, FS_UNIT * s + ) + hh = header_heights( + heads, + max((u.count("\n") + 1 for u in units if u), default=0), + col_groups is not None, + s, + fh, + unit_size=fu, + group_lines=max((t.count("\n") + 1 for t in titles), default=1), + group_size=fg, + ) + return fh, heads, fu, units, fg, titles, hh + barlabel = colorbar_label if barlabel is None: barlabel = ( @@ -413,22 +436,22 @@ def scorecard( cbar_w = 2.7 def _plan(cell: float): - fh, heads = fit_headings(heads_raw, lefts, cell * 72.0, FS_HEAD * s, FS_UNIT * s) - hh = header_heights(heads, unit_lines, col_groups is not None, s, fh) + header = _fit_header(cell * 72.0) + hh = header[-1] top_in = (hh["top"] + 4.0 * s) / 72.0 + (th.fs_title * 1.6 / 72.0 if title else 0.0) grid_w, grid_h = total_w * cell, total_h * cell extra = max(0.0, 0.5 * (cbar_w - grid_w)) + 0.06 l_in, r_in = max(left_in, extra), max(right_in, extra) bottom_in = (0.22 + 0.11 + (FS_CBAR_TICK + FS_CBAR) * s * 1.4 / 72.0 + 0.1) if colorbar else 0.08 - return fh, heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in + return header, grid_w, grid_h, l_in, r_in, top_in, bottom_in if width is not None: w_in = figure_size(width)[0] cell_for_wrap = _DEFAULT_CELL_IN for _ in range(3): # wrapping depends on the cell, the margins on the wrapping - _, _, _, _, _, l_in, r_in, _, _ = _plan(cell_for_wrap) + _, _, _, l_in, r_in, _, _ = _plan(cell_for_wrap) cell_for_wrap = max((w_in - l_in - r_in) / total_w, 0.05) - fh, heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in = _plan(cell_for_wrap) + header, grid_w, grid_h, l_in, r_in, top_in, bottom_in = _plan(cell_for_wrap) fig_w, fig_h = l_in + grid_w + r_in, top_in + grid_h + bottom_in fig = figure(width=fig_w, height=fig_h) ax = fig.add_axes([l_in / fig_w, bottom_in / fig_h, grid_w / fig_w, grid_h / fig_h]) @@ -439,8 +462,8 @@ def _plan(cell: float): fig = ax.figure box = ax.get_position() cell_pt = max(fig.get_figwidth() * box.width * 72.0 / total_w, 1.0) - fh, heads = fit_headings(heads_raw, lefts, cell_pt, FS_HEAD * s, FS_UNIT * s) - hh = header_heights(heads, unit_lines, col_groups is not None, s, fh) + header = _fit_header(cell_pt) + fh, heads, fu, units, fg, titles, hh = header ax.set_xlim(0, total_w) ax.set_ylim(total_h, 0) @@ -528,7 +551,19 @@ def _plan(cell: float): ) draw_header( - ax, lefts, heads, units, col_groups, hh, group_rule=group_rule, cell_pt=cell_pt, scale=s, head_size=fh + ax, + lefts, + heads, + units, + col_groups, + hh, + group_rule=group_rule, + cell_pt=cell_pt, + scale=s, + head_size=fh, + unit_size=fu, + group_titles=titles, + group_size=fg, ) if title: diff --git a/tests/test_scorecard.py b/tests/test_scorecard.py index 8b770d5..e018192 100644 --- a/tests/test_scorecard.py +++ b/tests/test_scorecard.py @@ -311,6 +311,25 @@ def test_a_unit_on_two_lines_keeps_clear_of_its_heading(): assert nf.check_text_overlaps(ax.figure) == [] +def test_group_titles_over_single_columns_shrink_and_wrap_until_neighbours_clear(): + groups = ["CATRINE D8.1", "dispersion"] * 3 + ax = _card([[1.0] * 6, [1.1] * 6], col_groups=groups) + titles = [t for t in ax.texts if t.get_text().replace("\n", " ") in set(groups)] + assert len(titles) == 6 + assert nf.check_text_overlaps(ax.figure) == [] + roomy = _card([[1.0] * 4, [1.1] * 4], col_groups=["In situ"] * 4) + assert [t.get_fontsize() for t in roomy.texts if t.get_text() == "In situ"] == [9.5] + + +def test_a_long_unit_under_adjacent_columns_wraps_clear_of_its_neighbours(): + unit = "Bq m⁻³ (STP)" + ax = _card( + [[1.0, 2.0, 3.0], [1.1, 2.1, 3.1]], col_units=dict.fromkeys(["c0", "c1", "c2"], unit), cell_in=0.36 + ) + assert len([t for t in ax.texts if t.get_text().replace("\n", " ") == unit]) == 3 + assert nf.check_text_overlaps(ax.figure) == [] + + def test_the_baseline_example_renders_without_text_problems_and_has_the_deck_look(): path = Path(__file__).parent.parent / "examples" / "34_scorecard_baseline.py" spec = importlib.util.spec_from_file_location("ex34", path)