Skip to content

Share subplots() label visibility handling with label_outer(). #19540

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 22, 2021
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
50 changes: 36 additions & 14 deletions lib/matplotlib/axes/_subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,22 +117,44 @@ def label_outer(self):
"""
Only show "outer" labels and tick labels.

x-labels are only kept for subplots on the last row; y-labels only for
subplots on the first column.
x-labels are only kept for subplots on the last row (or first row, if
labels are on the top side); y-labels only for subplots on the first
column (or last column, if labels are on the right side).
"""
self._label_outer_xaxis()
self._label_outer_yaxis()

def _label_outer_xaxis(self):
ss = self.get_subplotspec()
label_position = self.xaxis.get_label_position()
if not ss.is_first_row(): # Remove top label/ticklabels/offsettext.
if label_position == "top":
self.set_xlabel("")
self.xaxis.set_tick_params(which="both", labeltop=False)
if self.xaxis.offsetText.get_position()[1] == 1:
self.xaxis.offsetText.set_visible(False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part not tested?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is because moving offset texts is somewhat broken anyways (#19471).

if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext.
if label_position == "bottom":
self.set_xlabel("")
self.xaxis.set_tick_params(which="both", labelbottom=False)
if self.xaxis.offsetText.get_position()[1] == 0:
self.xaxis.offsetText.set_visible(False)

def _label_outer_yaxis(self):
ss = self.get_subplotspec()
lastrow = ss.is_last_row()
firstcol = ss.is_first_col()
if not lastrow:
for label in self.get_xticklabels(which="both"):
label.set_visible(False)
self.xaxis.get_offset_text().set_visible(False)
self.set_xlabel("")
if not firstcol:
for label in self.get_yticklabels(which="both"):
label.set_visible(False)
self.yaxis.get_offset_text().set_visible(False)
self.set_ylabel("")
label_position = self.yaxis.get_label_position()
if not ss.is_first_col(): # Remove left label/ticklabels/offsettext.
if label_position == "left":
self.set_ylabel("")
self.yaxis.set_tick_params(which="both", labelleft=False)
if self.yaxis.offsetText.get_position()[0] == 0:
self.yaxis.offsetText.set_visible(False)
if not ss.is_last_col(): # Remove right label/ticklabels/offsettext.
if label_position == "right":
self.set_ylabel("")
self.yaxis.set_tick_params(which="both", labelright=False)
if self.yaxis.offsetText.get_position()[0] == 1:
self.yaxis.offsetText.set_visible(False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...ditto


def _make_twin_axes(self, *args, **kwargs):
"""Make a twinx axes of self. This is used for twinx and twiny."""
Expand Down
20 changes: 4 additions & 16 deletions lib/matplotlib/gridspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,23 +309,11 @@ def subplots(self, *, sharex=False, sharey=False, squeeze=True,

# turn off redundant tick labeling
if sharex in ["col", "all"]:
for ax in axarr[:-1, :].flat: # Remove bottom labels/offsettexts.
ax.xaxis.set_tick_params(which="both", labelbottom=False)
if ax.xaxis.offsetText.get_position()[1] == 0:
ax.xaxis.offsetText.set_visible(False)
for ax in axarr[1:, :].flat: # Remove top labels/offsettexts.
ax.xaxis.set_tick_params(which="both", labeltop=False)
if ax.xaxis.offsetText.get_position()[1] == 1:
ax.xaxis.offsetText.set_visible(False)
for ax in axarr.flat:
ax._label_outer_xaxis()
if sharey in ["row", "all"]:
for ax in axarr[:, 1:].flat: # Remove left labels/offsettexts.
ax.yaxis.set_tick_params(which="both", labelleft=False)
if ax.yaxis.offsetText.get_position()[0] == 0:
ax.yaxis.offsetText.set_visible(False)
for ax in axarr[:, :-1].flat: # Remove right labels/offsettexts.
ax.yaxis.set_tick_params(which="both", labelright=False)
if ax.yaxis.offsetText.get_position()[0] == 1:
ax.yaxis.offsetText.set_visible(False)
for ax in axarr.flat:
ax._label_outer_yaxis()

if squeeze:
# Discarding unneeded dimensions that equal 1. If we only have one
Expand Down
26 changes: 25 additions & 1 deletion lib/matplotlib/tests/test_subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ def check_visible(axs, x_visible, y_visible):
for l in ax.get_yticklabels() + [ax.yaxis.offsetText]:
assert l.get_visible() == vy, \
f"Visibility of y axis #{i} is incorrectly {vy}"
# axis label "visibility" is toggled by label_outer by resetting the
# label to empty, but it can also be empty to start with.
if not vx:
assert ax.get_xlabel() == ""
if not vy:
assert ax.get_ylabel() == ""


def test_shared():
Expand Down Expand Up @@ -92,6 +98,7 @@ def test_shared():
f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=True, sharey=True)
axs = [a1, a2, a3, a4]
for ax in axs:
ax.set(xlabel="foo", ylabel="bar")
ax.label_outer()
check_visible(axs, [False, False, True, True], [True, False, True, False])

Expand Down Expand Up @@ -164,7 +171,7 @@ def test_subplots_offsettext():
@pytest.mark.parametrize("bottom", [True, False])
@pytest.mark.parametrize("left", [True, False])
@pytest.mark.parametrize("right", [True, False])
def test_subplots_hide_labels(top, bottom, left, right):
def test_subplots_hide_ticklabels(top, bottom, left, right):
# Ideally, we would also test offset-text visibility (and remove
# test_subplots_offsettext), but currently, setting rcParams fails to move
# the offset texts as well.
Expand All @@ -182,6 +189,23 @@ def test_subplots_hide_labels(top, bottom, left, right):
assert yright == (right and j == 2)


@pytest.mark.parametrize("xlabel_position", ["bottom", "top"])
@pytest.mark.parametrize("ylabel_position", ["left", "right"])
def test_subplots_hide_axislabels(xlabel_position, ylabel_position):
axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)
for (i, j), ax in np.ndenumerate(axs):
ax.set(xlabel="foo", ylabel="bar")
ax.xaxis.set_label_position(xlabel_position)
ax.yaxis.set_label_position(ylabel_position)
ax.label_outer()
assert bool(ax.get_xlabel()) == (
xlabel_position == "bottom" and i == 2
or xlabel_position == "top" and i == 0)
assert bool(ax.get_ylabel()) == (
ylabel_position == "left" and j == 0
or ylabel_position == "right" and j == 2)


def test_get_gridspec():
# ahem, pretty trivial, but...
fig, ax = plt.subplots()
Expand Down