Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ to [Semantic Versioning](https://semver.org/).
- **Behaviour change**: column headings are horizontal and wrapped, units are a grey second line,
group titles are regular weight above a 1.6 pt rule, row and column labels are text rather than
ticks, and the colourbar is half the grid width with ticks at the band edges and pointed ends.
- `scorecard` headings shrink from 7 pt towards the unit size (6 pt) until neighbouring headings stand
2 pt apart, so a word wider than a narrow cell no longer runs into the next heading.
- `outline_boxes` draws unfilled rectangles (`fill=False`).

### Fixed
Expand Down
41 changes: 36 additions & 5 deletions src/nicefigs/_scorecard.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,51 @@ def wrap_heading(label: str, size: float, width_pt: float) -> str:
return "\n".join(lines)


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]]:
"""The largest heading size, from ``size`` down to ``floor``, at which neighbouring headings 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.

Returns:
The size in points and the wrapped headings at that size (at ``floor`` if none clears).
"""
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
if all(p - half[j] - half[j + 1] >= clearance_pt for j, p in enumerate(pitch)):
return f, heads
return floor, heads


def header_heights(
headings: Sequence[str], unit_lines: int, has_groups: bool, scale: float
headings: Sequence[str], unit_lines: int, has_groups: bool, scale: float, head_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.
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``).

Returns:
``units`` and ``heading`` (bottoms of those texts), ``rule`` and ``group`` (the group rule
and the bottom of the group titles) and ``top`` (upper edge of the whole header).
"""
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
units = 3.0 * scale
heading = units + (unit_lines * FS_UNIT * _LINE * scale + 1.0 * scale if unit_lines else 0.0)
top = heading + n_lines * FS_HEAD * _LINE * 0.95 * scale + 1.0 * scale
top = heading + n_lines * head_size * _LINE * 0.95 + 1.0 * scale
rule = group = top
if has_groups:
rule = top + 3.0 * scale
Expand All @@ -94,8 +123,10 @@ def draw_header(
group_rule: bool,
cell_pt: float,
scale: float,
head_size: float | None = None,
) -> None:
"""Draw column headings, units, group titles and group rules above the grid."""
"""Draw column headings (at ``head_size`` pt, default ``FS_HEAD * scale``), units, group titles and rules."""
head_size = FS_HEAD * scale if head_size is None else head_size
for x, head, unit in zip(lefts, headings, units):
if unit:
ax.annotate(
Expand All @@ -116,7 +147,7 @@ def draw_header(
textcoords="offset points",
ha="center",
va="bottom",
fontsize=FS_HEAD * scale,
fontsize=head_size,
color=INK,
linespacing=0.95,
annotation_clip=False,
Expand Down
24 changes: 14 additions & 10 deletions src/nicefigs/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
FS_CBAR_TICK,
FS_HEAD,
FS_ROW,
FS_UNIT,
FS_VALUE,
NA_TEXT,
draw_colorbar,
draw_header,
fit_headings,
header_heights,
text_width_pt,
wrap_heading,
)
from .figure import figure_size
from .palettes import cmap as resolve_cmap
Expand Down Expand Up @@ -226,7 +227,8 @@ def scorecard(
``text`` is given. ``nan`` prints ``na_text`` on a grey cell.
row_labels: Row (model) names.
col_labels: Column (metric) names; wrapped at spaces to the cell width, or at your
own ``"\\n"``.
own ``"\\n"``. Headings shrink from 7 pt towards the unit size until neighbours stand
2 pt apart.
ax: Axes to draw on; a new figure sized from the cells is created if ``None``.
direction: ``{col_label: direction}`` with values from
:data:`~nicefigs.units.DIRECTIONS`; unlisted columns are ``"higher_better"``.
Expand Down Expand Up @@ -411,22 +413,22 @@ def scorecard(
cbar_w = 2.7

def _plan(cell: float):
heads = [wrap_heading(h, FS_HEAD * s, cell * 72.0 * 1.04) for h in heads_raw]
hh = header_heights(heads, unit_lines, col_groups is not None, s)
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)
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 heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in
return fh, heads, hh, 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)
heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in = _plan(cell_for_wrap)
fh, heads, hh, 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])
Expand All @@ -437,8 +439,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)
heads = [wrap_heading(h, FS_HEAD * s, cell_pt * 1.04) for h in heads_raw]
hh = header_heights(heads, unit_lines, col_groups is not None, s)
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)

ax.set_xlim(0, total_w)
ax.set_ylim(total_h, 0)
Expand Down Expand Up @@ -525,7 +527,9 @@ def _plan(cell: float):
annotation_clip=False,
)

draw_header(ax, lefts, heads, units, col_groups, hh, group_rule=group_rule, cell_pt=cell_pt, scale=s)
draw_header(
ax, lefts, heads, units, col_groups, hh, group_rule=group_rule, cell_pt=cell_pt, scale=s, head_size=fh
)

if title:
ax.set_title(title, fontsize=th.fs_title, pad=hh["top"] + 4.0 * s, loc="left")
Expand Down
13 changes: 13 additions & 0 deletions tests/test_scorecard.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,19 @@ def test_text_overlaps_are_clean_for_a_grouped_card_with_colourbar():
assert nf.check_text_overlaps(ax.figure) == []


def test_unbreakable_headings_shrink_until_neighbours_clear_and_roomy_ones_keep_7pt():
labels = ["OCO-2", "OCO-3", "TCCON"]
narrow = nf.scorecard(np.ones((1, 3)), row_labels=["a"], col_labels=labels, cell_in=0.31)
wide = nf.scorecard(np.ones((1, 3)), row_labels=["a"], col_labels=labels, cell_in=0.6)
heads = [t for t in narrow.texts if t.get_text() in labels]
assert all(6.0 <= t.get_fontsize() < 7.0 for t in heads)
assert {t.get_fontsize() for t in wide.texts if t.get_text() in labels} == {7.0}
narrow.figure.canvas.draw()
boxes = sorted((t.get_window_extent() for t in heads), key=lambda b: b.x0)
dpi = narrow.figure.dpi
assert all((b.x0 - a.x1) * 72.0 / dpi >= 1.5 for a, b in zip(boxes, boxes[1:]))


def test_a_unit_on_two_lines_keeps_clear_of_its_heading():
ax = _card(
[[1.0, 2.0], [0.9, 2.2]],
Expand Down
Loading