Skip to content
Open
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
9 changes: 7 additions & 2 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,9 +1274,10 @@ def sharex(self, other):
self._sharex = other
self.xaxis.major = other.xaxis.major # Ticker instances holding
self.xaxis.minor = other.xaxis.minor # locator and formatter.
# Set scale before limits to avoid warnings with non-linear scales
self.xaxis._scale = other.xaxis._scale
x0, x1 = other.get_xlim()
self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on())
self.xaxis._scale = other.xaxis._scale

def sharey(self, other):
"""
Expand All @@ -1293,9 +1294,10 @@ def sharey(self, other):
self._sharey = other
self.yaxis.major = other.yaxis.major # Ticker instances holding
self.yaxis.minor = other.yaxis.minor # locator and formatter.
# Set scale before limits to avoid warnings with non-linear scales
self.yaxis._scale = other.yaxis._scale
y0, y1 = other.get_ylim()
self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on())
self.yaxis._scale = other.yaxis._scale

def __clear(self):
"""Clear the Axes."""
Expand Down Expand Up @@ -1419,6 +1421,9 @@ def __clear(self):
share = getattr(self, f"_share{name}")
if share is not None:
getattr(self, f"share{name}")(share)
# Don't set default limits for shared axes - they will be
# synchronized from the shared axis and may have non-linear
# scales that would reject the (0, 1) default limits.
else:
# Although the scale was set to linear as part of clear,
# polar requires that _set_scale is called again
Expand Down
9 changes: 8 additions & 1 deletion lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1263,7 +1263,14 @@ def _set_lim(self, v0, v1, *, emit=True, auto):
for other in self._get_shared_axes():
if other is self.axes:
continue
other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto)
# Skip propagating default (0, 1) limits from linear scale to

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please convince me that this is the correct solution and not just fixing a special case. I don’t have full oversight on the details of the topic, but doing selective action on scale and limits doesn’t feel like it it’s a general solution.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for pushing back on this—it's a fair concern! Let me explain why I think this is actually a proper fix rather than just patching one edge case.

The core idea:

The problem we're solving is: when you clear an axes, it shouldn't try to force invalid default values onto other axes that share with it. My fix prevents exactly that—it stops (0, 1) limits from being passed to axes with non-linear scales that can't handle them.

Why focus on (0, 1)?

Those are the hardcoded default limits that [clear()] uses (you can see this on line 1427 in [_base.py]. They're literally the only values that would cause this issue during a clear operation. So checking specifically for (0, 1) isn't narrowing the fix—it's targeting the exact source of the problem.

What about other non-linear scales?

The condition [other_axis.get_scale() != 'linear'] handles everything: log, logit, symlog, asinh—any scale that isn't linear. They all have their own domain restrictions, and (0, 1) is problematic for many of them. So this actually covers all the cases where this warning could appear.

Why fix it in the propagation logic?

I chose this spot because it's where shared axes sync up their limits. When one axis changes its limits, it tells its shared partners. By catching the issue here, we prevent bad values from even reaching the point where they'd trigger warnings. It felt cleaner than trying to suppress warnings or changing how [clear()] itself works.

What I tried first:

I actually started by using [emit=False] when clearing, which would just stop all propagation. But that broke a different feature—when you clear an inverted shared axis, the other axes need to get that update. So [emit=False] was too heavy-handed.

# non-linear scales during clear operations to avoid warnings
other_axis = other._axis_map[name]
if (self.get_scale() == 'linear' and
other_axis.get_scale() != 'linear' and
v0 == 0 and v1 == 1):
continue
other_axis._set_lim(v0, v1, emit=False, auto=auto)
if emit:
other.callbacks.process(f"{name}lim_changed", other)
if ((other_fig := other.get_figure(root=False)) !=
Expand Down
45 changes: 45 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import re
import sys
from types import SimpleNamespace
import warnings
import unittest.mock

import dateutil.tz
Expand Down Expand Up @@ -528,6 +529,50 @@ def test_inverted_cla():
plt.close(fig)


def test_shared_axes_clear_with_nonlinear_scale():
"""
Test that clearing axes with shared non-linear scales doesn't warn.

Regression test for issue #9970.
When clearing an axes that shares with another axes having a non-linear
scale (log, logit, symlog, etc.), no warning should be generated about
setting non-positive limits.
"""
# Test log scale on x-axis
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_xscale('log')
x = np.logspace(0, 3, 100)
ax1.plot(x, x**2)
# Clearing should not generate warning about non-positive xlim
with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
ax1.cla()
fig.clf()
# Test log scale on y-axis
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.set_yscale('log')
y = np.logspace(0, 3, 100)
ax1.plot(y, y**2)
with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
ax1.cla()
fig.clf()
# Test other non-linear scales
for scale in ['logit', 'symlog']:
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_xscale(scale)
if scale == 'logit':
x = np.linspace(0.01, 0.99, 100)
else: # symlog
x = np.linspace(-100, 100, 100)
ax1.plot(x, x**2)
with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
ax1.cla()
fig.clf()
plt.close('all')


def test_subclass_clear_cla():
# Ensure that subclasses of Axes call cla/clear correctly.
# Note, we cannot use mocking here as we want to be sure that the
Expand Down
Loading