From e63b763db6862d26c8929aea1f9d46a977b9da85 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 11:26:27 +0200 Subject: [PATCH 1/7] Implement ticks on shared axes --- ultraplot/axes/cartesian.py | 35 +++++++++++++++ ultraplot/figure.py | 82 ++++++++++++++++++++++++++++++++++++ ultraplot/tests/test_axes.py | 64 ++++++++++++++++++++++++++++ 3 files changed, 181 insertions(+) diff --git a/ultraplot/axes/cartesian.py b/ultraplot/axes/cartesian.py index 2aa5a8be8..3be1c3433 100644 --- a/ultraplot/axes/cartesian.py +++ b/ultraplot/axes/cartesian.py @@ -901,6 +901,41 @@ def _validate_loc(loc, opts, descrip): kw.update({"label" + side: False for side in sides if side not in tickloc}) self.tick_params(axis=s, which="both", **kw) + # When axes are shared, the reference + # is the top left and bottom left plot + # for labels that are top or right + # this will plot them on thos first two plots + # we can fool mpl to share them by turning + # sharex/y off for those plots. We still + # update the ticks with the prior step, and + # keep the references in _shared_axes for all plots + labellright = kw.pop("labelright", None) + labeltop = kw.pop("labeltop", None) + + nrows, ncols = self.figure.gridspec.nrows, self.figure.gridspec.ncols + border_axes = {} + if labellright and self.figure._sharey or labeltop and self.figure._sharex: + border_axes = self.figure._get_border_axes() + # Only update if above is conditions above are true + for side, axs in border_axes.items(): + for axi in axs: + # Unset sharex/y otherwise ticks + # won't appear + if labellright and side == "right": + axi._sharey = None + axi.tick_params(labelright=labellright) + elif labellright and side == "left": + axi._sharey = None + if axi not in border_axes["right"]: + axi.tick_params(labelright=not labellright) + elif labeltop and side == "top": + axi._sharex = None + axi.tick_params(labeltop=labeltop) + elif labeltop and side == "bottom": + axi._sharex = None + if axi not in border_axes["top"]: + axi.tick_params(labeltop=not labeltop) + # Apply the axis label and offset label locations # Uses ugly mpl 3.3+ tick_top() tick_bottom() kludge for offset location # See: https://matplotlib.org/3.3.1/users/whats_new.html diff --git a/ultraplot/figure.py b/ultraplot/figure.py index cb52c5a9b..a6de166d6 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -7,6 +7,11 @@ import os from numbers import Integral +try: + from typing import List +except: + from typing_extensions import List + import matplotlib.axes as maxes import matplotlib.figure as mfigure import matplotlib.gridspec as mgridspec @@ -901,6 +906,83 @@ def _get_align_axes(self, side): axs = [ax for ax in axs if ax.get_visible()] return axs + def _get_border_axes(self) -> dict[str, list[paxes.Axes]]: + """ + Identifies axes located on the outer boundaries of the GridSpec layout. + + Returns a dictionary with keys 'top', 'bottom', 'left', 'right', each + containing a list of axes on that border. + """ + # Check if required attributes exist + if not hasattr(self, "gridspec") or not hasattr(self, "axes"): + warnings._warn_ultraplot("self.gridspec or self.axes not found.") + return dict(top=[], bottom=[], left=[], right=[]) + + gs = self.gridspec + all_axes = self.axes + + # Handle empty cases + nrows, ncols = gs.nrows, gs.ncols + if nrows == 0 or ncols == 0 or not all_axes: + return dict(top=[], bottom=[], left=[], right=[]) + + # Find occupied grid cells and valid axes + occupied_cells = set() + axes_with_spec = [] + + for axi in all_axes: + try: + spec = axi.get_subplotspec() + if spec is not None: + axes_with_spec.append((axi, spec)) + r0, r1 = spec.rowspan.start, spec.rowspan.stop + c0, c1 = spec.colspan.start, spec.colspan.stop + for r in range(r0, r1): + for c in range(c0, c1): + occupied_cells.add((r, c)) + except AttributeError: + pass + + if not axes_with_spec: + return dict(top=[], bottom=[], left=[], right=[]) + + # Initialize border axes sets + border_axes_sets = dict(top=set(), bottom=set(), left=set(), right=set()) + + # Check each axis against border criteria + for axi, spec in axes_with_spec: + r0, r1 = spec.rowspan.start, spec.rowspan.stop + c0, c1 = spec.colspan.start, spec.colspan.stop + + # Check top border + if r0 == 0 or ( + r0 == 1 and any((0, c) not in occupied_cells for c in range(c0, c1)) + ): + border_axes_sets["top"].add(axi) + + # Check bottom border + if r1 == nrows or ( + r1 == nrows - 1 + and any((nrows - 1, c) not in occupied_cells for c in range(c0, c1)) + ): + border_axes_sets["bottom"].add(axi) + + # Check left border + if c0 == 0 or ( + c0 == 1 and any((r, 0) not in occupied_cells for r in range(r0, r1)) + ): + border_axes_sets["left"].add(axi) + + # Check right border + if c1 == ncols or ( + c1 == ncols - 1 + and any((r, ncols - 1) not in occupied_cells for r in range(r0, r1)) + ): + border_axes_sets["right"].add(axi) + + # Convert sets to lists + return {key: list(val) for key, val in border_axes_sets.items()} + def _get_align_coord(self, side, axs, includepanels=False): """ Return the figure coordinate for centering spanning axis labels or super titles. diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 668a16fcc..4ac649925 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -187,3 +187,67 @@ def test_subset_format(): # Shorter than number of axs with pytest.raises(ValueError): axs.format(title=["a"]) + + +def test_sharing_labels_top_right(): + fig, ax = uplt.subplots(ncols=3, nrows=3, share="all") + # On the first format sharexy is modified + ax.format( + xticklabelloc="t", + yticklabelloc="r", + ) + # If we format again, we expect all the limits to be changed + # Plot on one shared axis a non-trivial point + # and check whether the limits are correctly adjusted + # for all other plots + ax[0].scatter([30, 40], [30, 40]) + xlim = ax[0].get_xlim() + ylim = ax[0].get_ylim() + + for axi in ax: + for i, j in zip(axi.get_xlim(), xlim): + assert i == j + for i, j in zip(axi.get_ylim(), ylim): + assert i == j + + +def test_sharing_labels_top_right_odd_layout(): + layout = [ + [1, 2, 0], + [1, 2, 5], + [3, 4, 5], + [3, 4, 0], + ] + fig, ax = uplt.subplots(layout) + ax.format( + xticklabelloc="t", + yticklabelloc="r", + ) + + def check_state(numbers: list, state: bool, which: str): + for number in numbers: + for label in getattr(ax[number], f"get_{which}ticklabels")(): + assert label.get_visible() == state + + check_state([0, 2], False, which="y") + check_state([1, 3, 4], True, which="y") + check_state([2, 3], False, which="x") + check_state([0, 1, 4], True, which="x") + uplt.close(fig) + + layout = [ + [1, 0, 2], + [0, 3, 0], + [4, 0, 5], + ] + + fig, ax = uplt.subplots(layout) + ax.format( + xticklabelloc="t", + yticklabelloc="r", + ) + check_state([0, 3], False, which="y") + check_state([1, 2, 4], True, which="y") + check_state([0, 1, 2], True, which="x") + check_state([3, 4], False, which="x") + uplt.close(fig) From 4c9212d5340402aff9f50bb934e39266fec01d47 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Fri, 25 Apr 2025 14:33:06 +0200 Subject: [PATCH 2/7] Update ultraplot/axes/cartesian.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- ultraplot/axes/cartesian.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/cartesian.py b/ultraplot/axes/cartesian.py index 3be1c3433..983a0730b 100644 --- a/ultraplot/axes/cartesian.py +++ b/ultraplot/axes/cartesian.py @@ -904,7 +904,7 @@ def _validate_loc(loc, opts, descrip): # When axes are shared, the reference # is the top left and bottom left plot # for labels that are top or right - # this will plot them on thos first two plots + # this will plot them on those first two plots # we can fool mpl to share them by turning # sharex/y off for those plots. We still # update the ticks with the prior step, and From 405bd6288fd6e163464579e5f5feb8c91d730492 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 14:43:17 +0200 Subject: [PATCH 3/7] rm safeguards as gridspec has no deleter --- ultraplot/figure.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index a6de166d6..4a3cd7218 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -914,9 +914,7 @@ def _get_border_axes(self) -> dict[str, list[paxes.Axes]]: containing a list of axes on that border. """ # Check if required attributes exist - if not hasattr(self, "gridspec") or not hasattr(self, "axes"): - warnings._warn_ultraplot("self.gridspec or self.axes not found.") - return dict(top=[], bottom=[], left=[], right=[]) + return dict(top=[], bottom=[], left=[], right=[]) gs = self.gridspec all_axes = self.axes @@ -931,17 +929,14 @@ def _get_border_axes(self) -> dict[str, list[paxes.Axes]]: axes_with_spec = [] for axi in all_axes: - try: - spec = axi.get_subplotspec() - if spec is not None: - axes_with_spec.append((axi, spec)) - r0, r1 = spec.rowspan.start, spec.rowspan.stop - c0, c1 = spec.colspan.start, spec.colspan.stop - for r in range(r0, r1): - for c in range(c0, c1): - occupied_cells.add((r, c)) - except AttributeError: - pass + spec = axi.get_subplotspec() + if spec is not None: + axes_with_spec.append((axi, spec)) + r0, r1 = spec.rowspan.start, spec.rowspan.stop + c0, c1 = spec.colspan.start, spec.colspan.stop + for r in range(r0, r1): + for c in range(c0, c1): + occupied_cells.add((r, c)) if not axes_with_spec: return dict(top=[], bottom=[], left=[], right=[]) From fb609ad0d8e87c095b284603c0f4c697afac26f9 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 14:46:00 +0200 Subject: [PATCH 4/7] rm safeguards as gridspec has no deleter --- ultraplot/figure.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 4a3cd7218..3e9eb8929 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -913,8 +913,6 @@ def _get_border_axes(self) -> dict[str, list[paxes.Axes]]: Returns a dictionary with keys 'top', 'bottom', 'left', 'right', each containing a list of axes on that border. """ - # Check if required attributes exist - return dict(top=[], bottom=[], left=[], right=[]) gs = self.gridspec all_axes = self.axes From bf791ddfeb69e4fceac7b25dd2ccbe20b14d2816 Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Fri, 25 Apr 2025 14:40:22 -0500 Subject: [PATCH 5/7] doc: add comment to make test clearer --- ultraplot/tests/test_axes.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 4ac649925..d0b1f83b0 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -229,6 +229,8 @@ def check_state(numbers: list, state: bool, which: str): for label in getattr(ax[number], f"get_{which}ticklabels")(): assert label.get_visible() == state + # these correspond to the indices of the axis + # in the axes array (so the grid number minus 1) check_state([0, 2], False, which="y") check_state([1, 3, 4], True, which="y") check_state([2, 3], False, which="x") @@ -246,6 +248,8 @@ def check_state(numbers: list, state: bool, which: str): xticklabelloc="t", yticklabelloc="r", ) + # these correspond to the indices of the axis + # in the axes array (so the grid number minus 1) check_state([0, 3], False, which="y") check_state([1, 2, 4], True, which="y") check_state([0, 1, 2], True, which="x") From 3db5b32795632c7bc0dd03cfbd774c141c5adcce Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 17:26:46 +0200 Subject: [PATCH 6/7] deal with sharex sharey --- ultraplot/axes/cartesian.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/cartesian.py b/ultraplot/axes/cartesian.py index 983a0730b..a1bf766af 100644 --- a/ultraplot/axes/cartesian.py +++ b/ultraplot/axes/cartesian.py @@ -923,16 +923,28 @@ def _validate_loc(loc, opts, descrip): # won't appear if labellright and side == "right": axi._sharey = None + siblings = list(axi._shared_axes["y"].get_siblings(axi)) + for sibling in siblings: + if sibling is axi: + continue + if sibling._sharey is not None: + continue + sibling._sharey = axi axi.tick_params(labelright=labellright) elif labellright and side == "left": - axi._sharey = None if axi not in border_axes["right"]: axi.tick_params(labelright=not labellright) elif labeltop and side == "top": axi._sharex = None + siblings = list(axi._shared_axes["x"].get_siblings(axi)) + for sibling in siblings: + if sibling is axi: + continue + if sibling._sharex is not None: + continue + sibling._sharex = axi axi.tick_params(labeltop=labeltop) elif labeltop and side == "bottom": - axi._sharex = None if axi not in border_axes["top"]: axi.tick_params(labeltop=not labeltop) From ae867a8f8a7c61e8c87d3a885952b948b7986601 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 27 Apr 2025 11:36:39 +0200 Subject: [PATCH 7/7] skip twinned --- ultraplot/axes/cartesian.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ultraplot/axes/cartesian.py b/ultraplot/axes/cartesian.py index a1bf766af..923ba227d 100644 --- a/ultraplot/axes/cartesian.py +++ b/ultraplot/axes/cartesian.py @@ -919,6 +919,8 @@ def _validate_loc(loc, opts, descrip): # Only update if above is conditions above are true for side, axs in border_axes.items(): for axi in axs: + if axi in self._twinned_axes: + continue # Unset sharex/y otherwise ticks # won't appear if labellright and side == "right":