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
4 changes: 4 additions & 0 deletions docs/subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
95 changes: 71 additions & 24 deletions ultraplot/gridspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions ultraplot/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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)])
Expand Down
55 changes: 47 additions & 8 deletions ultraplot/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,31 +970,70 @@ 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])
axs[2].plot([0, 1], [0, 1])
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])
axs[2].plot([0, 1], [0, 1])
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)


Expand Down
Loading
Loading