From 5ed8f99be29658e2379c4910a57796873a84f534 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 4 Nov 2026 19:54:28 +1000 Subject: [PATCH 1/3] Add constraints based on physical size rather than grid --- ultraplot/gridspec.py | 95 +++++++++--- ultraplot/tests/test_ultralayout.py | 176 +++++++++++++++++++++ ultraplot/ultralayout.py | 232 ++++++++++++++-------------- 3 files changed, 363 insertions(+), 140 deletions(-) diff --git a/ultraplot/gridspec.py b/ultraplot/gridspec.py index 2d89f5f4b..24188cc4f 100644 --- a/ultraplot/gridspec.py +++ b/ultraplot/gridspec.py @@ -1310,6 +1310,21 @@ def _auto_layout_tight(self, renderer): else: self.update() + def _get_axis_sizes( + self, which, *, total=None, reference=None, reference_size=None + ): + """Return physical track sizes using the subplot span constraints.""" + return ultralayout._solve_axis_sizes( + self._get_ultra_layout_array(), + 1 if which == "w" else 0, + getattr(self, f"_{which}ratios_total"), + [bool(value) for value in getattr(self, f"_{which}panels")], + getattr(self, f"{which}space_total"), + total=total, + reference=reference, + reference_size=reference_size, + ) + def _update_figsize(self): """ Return an updated auto layout figure size accounting for the @@ -1323,20 +1338,44 @@ def _update_figsize(self): return ss = ax.get_subplotspec().get_topmost_subplotspec() y1, y2, x1, x2 = ss._get_rows_columns() - # NOTE: Reference width/height should correspond to the span of the *axes* - # themselves. Spaces between rows/columns and adjacent panel slots should - # not reduce the target size; those are accounted for separately when the - # full figure size is rebuilt below. - refhspace = 0 - refwspace = 0 - refhpanel = 0 - refwpanel = 0 - refhsubplot = sum( - self.hratios_total[i] for i in range(y1, y2 + 1) if not self._hpanels[i] - ) # noqa: E501 - refwsubplot = sum( - self.wratios_total[i] for i in range(x1, x2 + 1) if not self._wpanels[i] - ) # noqa: E501 + + def _get_size(which, *, figure_size=None, reference_size=None): + start, stop = (x1, x2) if which == "w" else (y1, y2) + margin = self.left + self.right if which == "w" else self.bottom + self.top + spaces = getattr(self, f"{which}space_total") + if self._use_ultra_layout: + sizes = self._get_axis_sizes( + which, + total=None if figure_size is None else figure_size - margin, + reference=(start, stop), + reference_size=reference_size, + ) + figure_size = margin + sum(spaces) + sum(sizes) + reference_size = sum(sizes[start : stop + 1]) + sum(spaces[start:stop]) + else: + # Legacy placement includes all gaps and panel tracks inside a + # spanning axes. Account for these in both sizing directions. + ratios = getattr(self, f"{which}ratios_total") + panels = getattr(self, f"_{which}panels") + weight = sum(ratios[i] for i in range(start, stop + 1) if not panels[i]) + extra = sum(spaces[start:stop]) + sum( + ratios[i] for i in range(start, stop + 1) if panels[i] + ) + total_weight = self.gridwidth if which == "w" else self.gridheight + fixed = ( + self.spacewidth + self.panelwidth + if which == "w" + else self.spaceheight + self.panelheight + ) + if reference_size is None: + reference_size = ( + figure_size - fixed + ) * weight / total_weight + extra + else: + figure_size = ( + reference_size - extra + ) * total_weight / weight + fixed + return figure_size, reference_size # Get the reference sizes # NOTE: The sizing arguments should have been normalized already @@ -1349,16 +1388,14 @@ def _update_figsize(self): refaspect = _not_none(fig._refaspect, fig._refaspect_default) if refheight is None and figheight is None: if figwidth is not None: - gridwidth = figwidth - self.spacewidth - self.panelwidth - refwidth = gridwidth * refwsubplot / self.gridwidth + _, refwidth = _get_size("w", figure_size=figwidth) if refwidth is not None: # WARNING: do not change to elif! refheight = refwidth / refaspect else: raise RuntimeError("Figure size arguments are all missing.") if refwidth is None and figwidth is None: if figheight is not None: - gridheight = figheight - self.spaceheight - self.panelheight - refheight = gridheight * refhsubplot / self.gridheight + _, refheight = _get_size("h", figure_size=figheight) if refheight is not None: refwidth = refheight * refaspect else: @@ -1368,13 +1405,9 @@ def _update_figsize(self): # NOTE: For e.g. [[1, 1, 2, 2], [0, 3, 3, 0]] we make sure to still scale the # reference axes like a square even though takes two columns of gridspec. if refheight is not None: - refheight -= refhspace + refhpanel - gridheight = refheight * self.gridheight / refhsubplot - figheight = gridheight + self.spaceheight + self.panelheight + figheight, _ = _get_size("h", reference_size=refheight) if refwidth is not None: - refwidth -= refwspace + refwpanel - gridwidth = refwidth * self.gridwidth / refwsubplot - figwidth = gridwidth + self.spacewidth + self.panelwidth + figwidth, _ = _get_size("w", reference_size=refwidth) # Snap explicit reference-driven sizes to the pixel grid to avoid # rounding the axes width below the requested reference size. @@ -1637,6 +1670,20 @@ def get_grid_positions(self, figure=None): ) # noqa: E501 fig = _not_none(figure, self.figure) figwidth, figheight = fig.get_size_inches() + if self._use_ultra_layout: + widths = self._get_axis_sizes("w", total=figwidth - self.left - self.right) + heights = self._get_axis_sizes( + "h", total=figheight - self.top - self.bottom + ) + xedges = np.cumsum(np.column_stack(([0, *self.wspace_total], widths)).flat) + yedges = np.cumsum(np.column_stack(([0, *self.hspace_total], heights)).flat) + lefts, rights = ( + (self.left / figwidth + xedges / figwidth).reshape((-1, 2)).T + ) + tops, bottoms = ( + (1 - self.top / figheight - yedges / figheight).reshape((-1, 2)).T + ) + return bottoms, tops, lefts, rights spacewidth, spaceheight = self.spacewidth, self.spaceheight panelwidth, panelheight = self.panelwidth, self.panelheight hratios, wratios = self.hratios_total, self.wratios_total diff --git a/ultraplot/tests/test_ultralayout.py b/ultraplot/tests/test_ultralayout.py index 8a72b7aab..43d7c3076 100644 --- a/ultraplot/tests/test_ultralayout.py +++ b/ultraplot/tests/test_ultralayout.py @@ -402,3 +402,179 @@ def test_gridspec_copy_preserves_layout_array(): assert gs2._layout_array is not None assert np.array_equal(gs1._layout_array, gs2._layout_array) assert gs1._use_ultra_layout == gs2._use_ultra_layout + + +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("tight", [False, True]) +@pytest.mark.parametrize("bars", [(), (0,), (0, 2, 3, 4), (0, 1, 2, 3, 4)]) +def test_staggered_spans_preserve_sizes_and_local_guide_gaps(transpose, tight, bars): + """A guide changes its own interface, not axes sizes or other row gaps.""" + pytest.importorskip("kiwisolver") + layout = np.array([[1, 1, 2, 2, 3, 3], [0, 4, 4, 5, 5, 0]]) + if transpose: + layout = layout.T + side = "bottom" if transpose else "right" + space_key = "hspace" if transpose else "wspace" + x = np.array([-10, -5, 0, 5, 10]) + data = np.random.RandomState(51423).rand(5, 5) + for space in (0.1, 0.5): + fig, axs = uplt.subplots( + layout, + refwidth=2.2, + refaspect=1, + tight=tight, + **{space_key: f"{space}in"}, + ) + for i, ax in enumerate(axs): + kw = {} + if i in bars: + kw = dict(colorbar=side, colorbar_kw=dict(space="0.1in", width="0.2in")) + ax.contourf(x, x, data, **kw) + fig.canvas.draw() + size = fig.get_size_inches() + boxes = np.array([ax.get_position().bounds for ax in axs]) * np.tile(size, 2) + # Figure sizes are rounded up to pixels; allow at most one pixel. + np.testing.assert_allclose(boxes[:, 2:], 2.2, atol=1 / fig.dpi, rtol=0) + for first, second in ((0, 1), (1, 2), (3, 4)): + if transpose: + gap = boxes[first, 1] - boxes[second, 1] - boxes[second, 3] + else: + gap = boxes[second, 0] - boxes[first, 0] - boxes[first, 2] + assert gap == pytest.approx(space + (0.3 if first in bars else 0)) + if not bars: + # Equal empty half-slots keep the shorter row/column centred. + dim = 1 if transpose else 0 + outer_center = (boxes[0, dim] + boxes[2, dim] + boxes[0, dim + 2]) / 2 + inner_center = (boxes[3, dim] + boxes[4, dim] + boxes[3, dim + 2]) / 2 + assert inner_center == pytest.approx(outer_center) + for i in bars: + parent = axs[i].get_position() + panel = axs[i]._panel_dict[side][0].get_position() + if transpose: + assert panel.x0 == pytest.approx(parent.x0) + assert panel.width == pytest.approx(parent.width) + else: + assert panel.y0 == pytest.approx(parent.y0) + assert panel.height == pytest.approx(parent.height) + # Drawing again must not feed size changes back into tight layout. + fig.canvas.draw() + again = np.array([ax.get_position().bounds for ax in axs]) * np.tile( + fig.get_size_inches(), 2 + ) + np.testing.assert_allclose(again[:, 2:], boxes[:, 2:], atol=1 / fig.dpi, rtol=0) + uplt.close(fig) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_staggered_spans_respect_nonuniform_spacing(transpose): + layout = np.array([[1, 1, 2, 2, 3, 3], [0, 4, 4, 5, 5, 0]]) + if transpose: + layout = layout.T + fig, axs = uplt.subplots( + layout, + refwidth=2.2, + tight=False, + **{ + ("hspace" if transpose else "wspace"): [ + "0.05in", + "0.3in", + "0.2in", + "0.7in", + "0.1in", + ] + }, + ) + fig.canvas.draw() + boxes = np.array([ax.get_position().bounds for ax in axs]) * np.tile( + fig.get_size_inches(), 2 + ) + np.testing.assert_allclose(boxes[:, 2:], 2.2, atol=1 / fig.dpi, rtol=0) + for (a, b), expected in zip(((0, 1), (1, 2), (3, 4)), (0.3, 0.7, 0.2)): + gap = ( + boxes[a, 1] - boxes[b, 1] - boxes[b, 3] + if transpose + else boxes[b, 0] - boxes[a, 0] - boxes[a, 2] + ) + assert gap == pytest.approx(expected) + + +@pytest.mark.parametrize("ultra_layout", [False, True]) +@pytest.mark.parametrize("sizing", ["refwidth", "refheight", "figwidth", "figheight"]) +def test_spanning_reference_aspect_with_internal_spacing(ultra_layout, sizing): + """Reference and figure sizing agree with the actual reference axes box.""" + fig, axs = uplt.subplots( + [[1, 1, 2], [3, 3, 2]], + refaspect=1.5, + ultra_layout=ultra_layout, + tight=False, + wspace="0.4in", + hspace="0.3in", + **{sizing: 2.2 if sizing.startswith("ref") else 7}, + ) + fig.canvas.draw() + size = fig.get_size_inches() + box = axs[0].get_position() + width, height = box.width * size[0], box.height * size[1] + assert width / height == pytest.approx(1.5, abs=0.01) + if sizing == "refwidth": + assert width == pytest.approx(2.2, abs=1 / fig.dpi) + elif sizing == "refheight": + assert height == pytest.approx(2.2, abs=1 / fig.dpi) + else: + assert size[0 if sizing == "figwidth" else 1] == pytest.approx(7) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_spanning_axes_cover_adjacent_stack_with_panels(transpose): + """A larger span still covers smaller axes and the panel/gap between them.""" + layout = np.array([[1, 2], [1, 3]]) + if transpose: + layout = layout.T + fig, axs = uplt.subplots(layout, refwidth=2.2, tight=False, space="0.3in") + axs[1].panel_axes("right" if transpose else "bottom", width="0.2in", space="0.1in") + fig.canvas.draw() + span, first, last = [ax.get_position() for ax in axs] + if transpose: + assert span.x0 == pytest.approx(first.x0) + assert span.x1 == pytest.approx(last.x1) + else: + assert span.y1 == pytest.approx(first.y1) + assert span.y0 == pytest.approx(last.y0) + + +def test_staggered_spans_with_panels_and_fixed_figure_size(): + widths = [] + for space in ("0.2in", "0.5in"): + fig, axs = uplt.subplots( + [[1, 1, 2, 2, 3, 3], [0, 4, 4, 5, 5, 0]], + figsize=(9, 6), + tight=False, + wspace=space, + ) + for i in (0, 2, 3, 4): + axs[i].panel_axes("right", width="0.2in", space="0.1in") + fig.canvas.draw() + np.testing.assert_allclose(fig.get_size_inches(), (9, 6)) + sizes = [ax.get_position().width * 9 for ax in axs] + np.testing.assert_allclose(sizes, sizes[0]) + widths.append(sizes[0]) + uplt.close(fig) + assert widths[1] < widths[0] + + +@pytest.mark.parametrize("side", ["left", "right", "top", "bottom"]) +def test_staggered_spans_with_stacked_panels(side): + layout = np.array([[1, 1, 2, 2, 3, 3], [0, 4, 4, 5, 5, 0]]) + if side in ("top", "bottom"): + layout = layout.T + fig, axs = uplt.subplots(layout, refwidth=2.2, tight=False, space="0.3in") + # Add guides in reverse axes order and stack two on each parent. + for i in (4, 3, 2, 0): + for _ in range(2): + axs[i].panel_axes(side, width="0.2in", space="0.1in") + fig.canvas.draw() + sizes = np.array( + [[ax.get_position().width, ax.get_position().height] for ax in axs] + ) + sizes *= fig.get_size_inches() + np.testing.assert_allclose(sizes, 2.2, atol=1 / fig.dpi, rtol=0) diff --git a/ultraplot/ultralayout.py b/ultraplot/ultralayout.py index 5aa2efdfa..660d7ca0a 100644 --- a/ultraplot/ultralayout.py +++ b/ultraplot/ultralayout.py @@ -140,6 +140,103 @@ def is_orthogonal_layout(array: np.ndarray) -> bool: return True +def _solve_axis_sizes( + array, + axis, + ratios, + panels, + spaces, + *, + total=None, + reference=None, + reference_size=None, +): + """Size grid tracks by their visible subplot spans, in physical units. + + Panel tracks and gaps have fixed sizes. Ordinary tracks are subdivisions + of axes, not necessarily axes themselves: constraining their ratios would + let a gap or a panel inside a span change the size of that subplot. + + Constrain the smallest subplot intervals to a common scale instead. A + larger interval containing these intervals inherits their sizes and the + intervening gaps, as in a conventional spanning subplot. The reference + span or the total extent fixes the scale. Any remaining freedom is resolved + by a least-squares preference for the original track ratios; this treats + equivalent left/right (or top/bottom) subdivisions symmetrically. + """ + ratios = np.asarray(ratios, dtype=float) + panels = np.asarray(panels, dtype=bool) + spaces = np.asarray(spaces, dtype=float) + ordinary = np.flatnonzero(~panels) + fixed = np.where(panels, ratios, 0.0) + intervals = set() + for num in np.unique(array[array != 0]): + indices = np.where(array == num)[axis] + intervals.add((int(indices.min()), int(indices.max()))) + minimal = [ + (lo, hi) + for lo, hi in sorted(intervals) + if not any(lo <= a <= b <= hi and (a, b) != (lo, hi) for a, b in intervals) + ] + # Empty tracks still participate in the layout and retain their ratios. + if not minimal: + minimal = [(int(i), int(i)) for i in ordinary] + + # Regular grids (including larger axes spanning a stack of smaller ones) + # have a scalar solution. Avoid a matrix decomposition on the common path. + if minimal == [(int(i), int(i)) for i in ordinary]: + if reference_size is None: + scale = (total - fixed.sum() - spaces.sum()) / ratios[ordinary].sum() + else: + lo, hi = reference + mask = (ordinary >= lo) & (ordinary <= hi) + offset = fixed[lo : hi + 1].sum() + spaces[lo:hi].sum() + scale = (reference_size - offset) / ratios[ordinary[mask]].sum() + fixed[ordinary] = ratios[ordinary] * scale + return fixed + + def span(lo, hi): + mask = (ordinary >= lo) & (ordinary <= hi) + row = np.zeros(len(ordinary) + 1) + row[:-1] = mask + offset = fixed[lo : hi + 1].sum() + spaces[lo:hi].sum() + return row, offset, ratios[ordinary[mask]].sum() + + rows, values = [], [] + for lo, hi in minimal: + row, offset, weight = span(lo, hi) + if not weight: + continue + row[-1] = -weight + rows.append(row) + values.append(-offset) + if reference_size is None: + row, offset, _ = span(0, len(ratios) - 1) + value = total - offset + else: + row, offset, _ = span(*reference) + value = reference_size - offset + rows.append(row) + values.append(value) + matrix = np.asarray(rows) + values = np.asarray(values) + solution, _, rank, _ = np.linalg.lstsq(matrix, values, rcond=None) + # Minimize track-ratio error within the null space of the span constraints, + # rather than weakening the physical reference-size or spacing constraints. + if rank < matrix.shape[1]: + _, _, vectors = np.linalg.svd(matrix, full_matrices=True) + null = vectors[rank:].T + preference = np.column_stack((np.eye(len(ordinary)), -ratios[ordinary])) + correction = np.linalg.lstsq( + preference @ null, -preference @ solution, rcond=None + )[0] + solution += null @ correction + if not np.allclose(matrix @ solution, values, rtol=1e-9, atol=1e-9): + raise ValueError("Inconsistent subplot span sizes.") + fixed[ordinary] = solution[:-1] + return fixed + + class UltraLayoutSolver: """ UltraLayout: Constraint-based layout solver using kiwisolver for subplot positioning. @@ -284,54 +381,26 @@ def _setup_constraints(self): self.row_bottoms[i] == self.row_tops[i + 1] + spacing ) - # 4. Width constraints (panel slots are fixed, remaining slots use ratios) - total_width = 1.0 - (self.left_margin + self.right_margin) / self.figwidth - if self.ncols > 1: - spacing_total = sum(self.wspace) / self.figwidth - else: - spacing_total = 0 - available_width = total_width - spacing_total - fixed_width = 0.0 - ratio_sum = 0.0 - for i in range(self.ncols): - if self.wpanels[i]: - fixed_width += self.wratios[i] / self.figwidth - else: - ratio_sum += self.wratios[i] - remaining_width = max(0.0, available_width - fixed_width) - if ratio_sum == 0: - ratio_sum = 1.0 - - for i in range(self.ncols): - if self.wpanels[i]: - width = self.wratios[i] / self.figwidth - else: - width = remaining_width * self.wratios[i] / ratio_sum + # Size visible subplot spans, including any fixed slots inside them. + widths = _solve_axis_sizes( + self.array, + 1, + self.wratios, + self.wpanels, + self.wspace, + total=self.figwidth - self.left_margin - self.right_margin, + ) + heights = _solve_axis_sizes( + self.array, + 0, + self.hratios, + self.hpanels, + self.hspace, + total=self.figheight - self.top_margin - self.bottom_margin, + ) + for i, width in enumerate(widths / self.figwidth): self.solver.addConstraint(self.col_rights[i] == self.col_lefts[i] + width) - - # 5. Height constraints (panel slots are fixed, remaining slots use ratios) - total_height = 1.0 - (self.top_margin + self.bottom_margin) / self.figheight - if self.nrows > 1: - spacing_total = sum(self.hspace) / self.figheight - else: - spacing_total = 0 - available_height = total_height - spacing_total - fixed_height = 0.0 - ratio_sum = 0.0 - for i in range(self.nrows): - if self.hpanels[i]: - fixed_height += self.hratios[i] / self.figheight - else: - ratio_sum += self.hratios[i] - remaining_height = max(0.0, available_height - fixed_height) - if ratio_sum == 0: - ratio_sum = 1.0 - - for i in range(self.nrows): - if self.hpanels[i]: - height = self.hratios[i] / self.figheight - else: - height = remaining_height * self.hratios[i] / ratio_sum + for i, height in enumerate(heights / self.figheight): self.solver.addConstraint(self.row_tops[i] == self.row_bottoms[i] + height) def solve(self) -> Dict[int, Tuple[float, float, float, float]]: @@ -353,55 +422,6 @@ def solve(self) -> Dict[int, Tuple[float, float, float, float]]: col_rights = [v.value() for v in self.col_rights] row_tops = [v.value() for v in self.row_tops] row_bottoms = [v.value() for v in self.row_bottoms] - col_widths = [right - left for left, right in zip(col_lefts, col_rights)] - row_heights = [top - bottom for top, bottom in zip(row_tops, row_bottoms)] - - base_wgap = None - for i in range(self.ncols - 1): - if not self.wpanels[i] and not self.wpanels[i + 1]: - gap = col_lefts[i + 1] - col_rights[i] - if base_wgap is None or gap < base_wgap: - base_wgap = gap - if base_wgap is None: - base_wgap = 0.0 - - base_hgap = None - for i in range(self.nrows - 1): - if not self.hpanels[i] and not self.hpanels[i + 1]: - gap = row_bottoms[i] - row_tops[i + 1] - if base_hgap is None or gap < base_hgap: - base_hgap = gap - if base_hgap is None: - base_hgap = 0.0 - - def _adjust_span( - spans: List[int], - start: float, - end: float, - sizes: List[float], - panels: List[bool], - base_gap: float, - ) -> Tuple[float, float]: - effective = [i for i in spans if not panels[i]] - if len(effective) <= 1: - return start, end - # Preserve normal gaps between non-panel slots while collapsing - # gaps introduced by panel slots inside the span. - gap_count = 0 - for idx in range(len(spans) - 1): - i = spans[idx] - j = spans[idx + 1] - if not panels[i] and not panels[j]: - gap_count += 1 - desired = sum(sizes[i] for i in effective) + base_gap * gap_count - # Collapse inter-column/row gaps inside spans to keep widths consistent. - # This avoids widening subplots that cross internal panel slots. - full = end - start - if desired < full: - offset = 0.5 * (full - desired) - start = start + offset - end = start + desired - return start, end for num in self.subplot_nums: rows, cols = np.where(self.array == num) @@ -414,26 +434,6 @@ def _adjust_span( bottom = row_bottoms[row_max] top = row_tops[row_min] - span_cols = list(range(col_min, col_max + 1)) - span_rows = list(range(row_min, row_max + 1)) - - left, right = _adjust_span( - span_cols, - left, - right, - col_widths, - self.wpanels, - base_wgap, - ) - top, bottom = _adjust_span( - span_rows, - top, - bottom, - row_heights, - self.hpanels, - base_hgap, - ) - width = right - left height = top - bottom From 8cf21b985325fa520cd95b43ceaeb033a53f8575 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 4 Nov 2026 21:06:05 +1000 Subject: [PATCH 2/3] Prevent inverted axes when layout space is exhausted --- docs/subplots.py | 4 +++ ultraplot/tests/test_axes.py | 4 +++ ultraplot/tests/test_ultralayout.py | 41 +++++++++++++++++++++++++++++ ultraplot/ultralayout.py | 10 +++++-- 4 files changed, 57 insertions(+), 2 deletions(-) diff --git a/docs/subplots.py b/docs/subplots.py index f899751ac..7d7ce5d16 100644 --- a/docs/subplots.py +++ b/docs/subplots.py @@ -139,6 +139,10 @@ # subplot spacing and the reference subplot aspect ratio `refaspect` (default # is ``1`` unless the data aspect ratio is fixed -- see below). If both the # width and height are specified, then `refaspect` is ignored. +# These sizes describe the visible reference axes, including when it spans +# several cells in a layout array. Changing `wspace` or `hspace` then changes +# the figure size to preserve the requested axes size. With a fixed `figsize`, +# increasing spacing instead reduces the space available for the axes. # * `figwidth` and `figheight` set the physical width and height of the figure. # As in matplotlib, you can use `figsize` to set both at once. If just the width # (height) is specified, then the height (width) is automatically adjusted, just diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 83027c727..a41387291 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -355,6 +355,8 @@ def test_title_shifts_when_abc_overlaps_different_loc(): fig.canvas.draw() assert title_obj.get_fontsize() == original_size assert title_obj.get_position()[0] > original_x + assert axs[0].get_position().width >= 0 + assert axs[0].get_position().height >= 0 def test_centered_title_does_not_shift_for_inset_abc(): @@ -445,6 +447,8 @@ def test_title_shifts_centered_left_of_abc(): fig.canvas.draw() assert title_obj.get_fontsize() == original_size assert title_obj.get_position()[0] < original_x + assert axs[0].get_position().width >= 0 + assert axs[0].get_position().height >= 0 ticks = axs[0].get_xticks() assert ticks.size > 0 xy = np.column_stack([ticks, np.zeros_like(ticks)]) diff --git a/ultraplot/tests/test_ultralayout.py b/ultraplot/tests/test_ultralayout.py index 43d7c3076..bb220777c 100644 --- a/ultraplot/tests/test_ultralayout.py +++ b/ultraplot/tests/test_ultralayout.py @@ -578,3 +578,44 @@ def test_staggered_spans_with_stacked_panels(side): ) sizes *= fig.get_size_inches() np.testing.assert_allclose(sizes, 2.2, atol=1 / fig.dpi, rtol=0) + + +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("spanning", [False, True]) +def test_exhausted_figure_space_does_not_invert_axes(transpose, spanning): + """Oversized margins collapse visible spans instead of mirroring axes.""" + layout = np.array([[1, 1, 2, 2], [0, 3, 3, 0]] if spanning else [[1, 2]]) + if transpose: + layout = layout.T + positions = ultralayout.compute_ultra_positions( + layout, + figwidth=2, + figheight=2, + **({"top": 1, "bottom": 2} if transpose else {"left": 1, "right": 2}), + ) + for left, bottom, width, height in positions.values(): + assert np.isfinite((left, bottom, width, height)).all() + assert width >= 0 + assert height >= 0 + assert (height if transpose else width) == 0 + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_wide_spacing_does_not_clamp_virtual_tracks(transpose): + """Large gaps may require negative subdivisions inside positive spans.""" + layout = np.array([[1, 1, 2, 2, 3, 3], [0, 4, 4, 5, 5, 0]]) + if transpose: + layout = layout.T + fig, axs = uplt.subplots( + layout, + refwidth=1, + refaspect=1, + tight=False, + **{("hspace" if transpose else "wspace"): "2in"}, + ) + fig.canvas.draw() + sizes = np.array( + [[ax.get_position().width, ax.get_position().height] for ax in axs] + ) + sizes *= fig.get_size_inches() + np.testing.assert_allclose(sizes, 1, atol=1 / fig.dpi, rtol=0) diff --git a/ultraplot/ultralayout.py b/ultraplot/ultralayout.py index 660d7ca0a..d89154e1e 100644 --- a/ultraplot/ultralayout.py +++ b/ultraplot/ultralayout.py @@ -430,9 +430,15 @@ def solve(self) -> Dict[int, Tuple[float, float, float, float]]: # Get the bounding box from the grid lines left = col_lefts[col_min] - right = col_rights[col_max] + right = max(left, col_rights[col_max]) bottom = row_bottoms[row_max] - top = row_tops[row_min] + top = max(bottom, row_tops[row_min]) + + # Tight margins can exhaust a fixed-size figure (e.g. a title + # wider than the canvas). Match SubplotSpec's legacy behavior: + # collapse the visible axes instead of reversing its transform. + # Do not clamp individual tracks: these are virtual subdivisions + # and can be negative while their containing subplot stays valid. width = right - left height = top - bottom From 6508375c1b075fcfc5a7d46985d7fa95671e95e1 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 4 Nov 2026 22:03:44 +1000 Subject: [PATCH 3/3] Make aspect-span alignment tests independent of rounding --- ultraplot/tests/test_figure.py | 55 +++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 5714d7100..05757c8d2 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -970,8 +970,12 @@ def test_align_spanning_axes_no_axes(): uplt.close(fig) -def test_aspect_row_spanning_layout(): - fig, axs = uplt.subplots([[1, 2], [1, 3]]) +@pytest.mark.parametrize("dpi", [72, 100, 144]) +def test_aspect_row_spanning_layout(dpi): + # Auto sizing can already satisfy the reference aspect, leaving no span + # to remap (or just a platform-dependent pixel-rounding discrepancy). + # Use a deliberately tall slot so equal aspect must reduce its height. + fig, axs = uplt.subplots([[1, 2], [1, 3]], figsize=(4, 6), tight=False, dpi=dpi) axs[0].set_aspect("equal") axs[0].plot([0, 1], [0, 1]) axs[1].plot([0, 1], [0, 1]) @@ -979,13 +983,20 @@ def test_aspect_row_spanning_layout(): fig.canvas.draw() axes = list(fig._iter_axes(hidden=False, children=False, panels=False)) spans = fig._find_misaligned_spans(axes) - assert len(spans) >= 1 - assert any(s[0] == "y" for s in spans) + assert len(spans) == 1 + direction, _, _, slot, pos, ref_ax = spans[0] + assert direction == "y" + assert ref_ax is axs[0] + assert pos.height < slot.height + assert axs[1].get_position().y1 == pytest.approx(pos.y1) + assert axs[2].get_position().y0 == pytest.approx(pos.y0) uplt.close(fig) -def test_aspect_col_spanning_layout(): - fig, axs = uplt.subplots([[1, 1], [2, 3]]) +@pytest.mark.parametrize("dpi", [72, 100, 144]) +def test_aspect_col_spanning_layout(dpi): + # A fixed wide slot guarantees that equal aspect must reduce its width. + fig, axs = uplt.subplots([[1, 1], [2, 3]], figsize=(6, 4), tight=False, dpi=dpi) axs[0].set_aspect("equal") axs[0].plot([0, 1], [0, 1]) axs[1].plot([0, 1], [0, 1]) @@ -993,8 +1004,36 @@ def test_aspect_col_spanning_layout(): fig.canvas.draw() axes = list(fig._iter_axes(hidden=False, children=False, panels=False)) spans = fig._find_misaligned_spans(axes) - assert len(spans) >= 1 - assert any(s[0] == "x" for s in spans) + assert len(spans) == 1 + direction, _, _, slot, pos, ref_ax = spans[0] + assert direction == "x" + assert ref_ax is axs[0] + assert pos.width < slot.width + assert axs[1].get_position().x0 == pytest.approx(pos.x0) + assert axs[2].get_position().x1 == pytest.approx(pos.x1) + uplt.close(fig) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_aspect_spanning_layout_already_aligned(transpose): + layout = np.array([[1, 2], [1, 3]]) + if transpose: + layout = layout.T + fig, axs = uplt.subplots( + layout, + refwidth=2, + refheight=2, + tight=False, + dpi=100, + left="0.5in", + right="0.5in", + top="0.5in", + bottom="0.5in", + space="0.5in", + ) + axs[0].format(aspect="equal", xlim=(0, 1), ylim=(0, 1)) + fig.canvas.draw() + assert fig._find_misaligned_spans(list(axs)) == [] uplt.close(fig)