Skip to content

Commit 4e059bc

Browse files
authored
Merge pull request #23417 from dstansby/unit-axis-label
Consistently set label on axis with units
2 parents 312fdb7 + a5a4f2c commit 4e059bc

File tree

5 files changed

+30
-1
lines changed

5 files changed

+30
-1
lines changed

lib/matplotlib/axes/_base.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2629,7 +2629,9 @@ def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True):
26292629
except KeyError:
26302630
raise ValueError(f"Invalid axis name: {axis_name!r}") from None
26312631
# Update from data if axis is already set but no unit is set yet.
2632-
if axis is not None and data is not None and not axis.have_units():
2632+
if (axis is not None and
2633+
data is not None and
2634+
not axis._have_units_and_converter()):
26332635
axis.update_units(data)
26342636
for axis_name, axis in axis_map.items():
26352637
# Return if no axis is set.

lib/matplotlib/axis.py

+9
Original file line numberDiff line numberDiff line change
@@ -1715,8 +1715,17 @@ def _update_axisinfo(self):
17151715
self.set_default_intervals()
17161716

17171717
def have_units(self):
1718+
"""
1719+
Return `True` if units or a converter have been set.
1720+
"""
17181721
return self.converter is not None or self.units is not None
17191722

1723+
def _have_units_and_converter(self):
1724+
"""
1725+
Return `True` if units and a converter have been set.
1726+
"""
1727+
return self.converter is not None and self.units is not None
1728+
17201729
def convert_units(self, x):
17211730
# If x is natively supported by Matplotlib, doesn't need converting
17221731
if munits._is_natively_supported(x):

lib/matplotlib/testing/jpl_units/UnitDbl.py

+2
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ def __bool__(self):
9191

9292
def _cmp(self, op, rhs):
9393
"""Check that *self* and *rhs* share units; compare them using *op*."""
94+
if rhs is None:
95+
return NotImplemented
9496
self.checkSameUnits(rhs, "compare")
9597
return op(self._value, rhs._value)
9698

lib/matplotlib/tests/test_units.py

+16
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,19 @@ def test_plot_kernel():
283283
# just a smoketest that fail
284284
kernel = Kernel([1, 2, 3, 4, 5])
285285
plt.plot(kernel)
286+
287+
288+
@pytest.mark.parametrize('plot_meth_name', ['scatter', 'plot'])
289+
def test_unit_axis_label(plot_meth_name):
290+
# Check that the correct Axis labels are set on plots with units
291+
import matplotlib.testing.jpl_units as units
292+
units.register()
293+
294+
fig, ax = plt.subplots()
295+
ax.xaxis.set_units('m')
296+
ax.yaxis.set_units('sec')
297+
plot_method = getattr(ax, plot_meth_name)
298+
plot_method(np.arange(3) * units.m, np.arange(3) * units.sec)
299+
assert ax.get_xlabel() == 'm'
300+
assert ax.get_ylabel() == 'sec'
301+
plt.close('all')

0 commit comments

Comments
 (0)