Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f77c0a5

Browse files
committed
Add set_xunits and set_yunits
1 parent ce6ac2d commit f77c0a5

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4305,3 +4305,37 @@ def get_shared_x_axes(self):
43054305
def get_shared_y_axes(self):
43064306
"""Return a reference to the shared axes Grouper object for y axes."""
43074307
return self._shared_y_axes
4308+
4309+
def set_xunits(self, units, emit=True):
4310+
"""
4311+
Set the x-axis units.
4312+
4313+
Parameters
4314+
----------
4315+
units : units tag
4316+
4317+
emit : bool, default: True
4318+
Whether to notify observers of units change.
4319+
"""
4320+
if emit:
4321+
for ax in self._shared_x_axes.get_siblings(self):
4322+
ax.xaxis.set_units(units)
4323+
else:
4324+
self.xaxis.set_units(units)
4325+
4326+
def set_yunits(self, units, emit=True):
4327+
"""
4328+
Set the y-axis units.
4329+
4330+
Parameters
4331+
----------
4332+
units : units tag
4333+
4334+
emit : bool, default: True
4335+
Whether to notify observers of units change.
4336+
"""
4337+
if emit:
4338+
for ax in self._shared_y_axes.get_siblings(self):
4339+
ax.yaxis.set_units(units)
4340+
else:
4341+
self.yaxis.set_units(units)

lib/matplotlib/tests/test_units.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,28 @@ class subdate(datetime):
172172

173173
fig_test.subplots().plot(subdate(2000, 1, 1), 0, "o")
174174
fig_ref.subplots().plot(datetime(2000, 1, 1), 0, "o")
175+
176+
177+
def test_set_xyunits(quantity_converter):
178+
munits.registry[Quantity] = quantity_converter
179+
x = Quantity(np.linspace(0, 1, 10), "hours")
180+
y1 = Quantity(np.linspace(1, 2, 10), "feet")
181+
y2 = Quantity(np.linspace(3, 4, 10), "feet")
182+
fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all')
183+
ax1.plot(x, y1)
184+
ax2.plot(x, y2)
185+
assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "hours"
186+
assert ax2.yaxis.get_units() == ax2.yaxis.get_units() == "feet"
187+
ax1.set_xunits("seconds")
188+
ax2.set_yunits("inches")
189+
assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "seconds"
190+
assert ax1.yaxis.get_units() == ax2.yaxis.get_units() == "inches"
191+
fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all')
192+
ax1.plot(x, y1)
193+
ax2.plot(x, y2)
194+
ax1.set_xunits("seconds", emit=False)
195+
ax2.set_yunits("inches", emit=False)
196+
assert ax1.xaxis.get_units() == "seconds"
197+
assert ax2.xaxis.get_units() == "hours"
198+
assert ax1.yaxis.get_units() == "feet"
199+
assert ax2.yaxis.get_units() == "inches"

0 commit comments

Comments
 (0)