Skip to content

Commit c536c07

Browse files
committed
feat: axes class and kwargs for twinx and twiny
1 parent e1c76a0 commit c536c07

File tree

3 files changed

+39
-7
lines changed

3 files changed

+39
-7
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4596,7 +4596,7 @@ def _make_twin_axes(self, *args, **kwargs):
45964596
self._twinned_axes.join(self, twin)
45974597
return twin
45984598

4599-
def twinx(self):
4599+
def twinx(self, **kwargs):
46004600
"""
46014601
Create a twin Axes sharing the xaxis.
46024602
@@ -4606,6 +4606,11 @@ def twinx(self):
46064606
Axes. To ensure that the tick marks of both y-axes align, see
46074607
`~matplotlib.ticker.LinearLocator`.
46084608
4609+
Parameters
4610+
----------
4611+
kwargs : dict
4612+
The keyword arguments passed to ``add_subplot()`` or ``add_axes()``.
4613+
46094614
Returns
46104615
-------
46114616
Axes
@@ -4616,7 +4621,7 @@ def twinx(self):
46164621
For those who are 'picking' artists while using twinx, pick
46174622
events are only called for the artists in the top-most Axes.
46184623
"""
4619-
ax2 = self._make_twin_axes(sharex=self)
4624+
ax2 = self._make_twin_axes(sharex=self, axes_class=type(self), **kwargs)
46204625
ax2.yaxis.tick_right()
46214626
ax2.yaxis.set_label_position('right')
46224627
ax2.yaxis.set_offset_position('right')
@@ -4627,7 +4632,7 @@ def twinx(self):
46274632
ax2.xaxis.units = self.xaxis.units
46284633
return ax2
46294634

4630-
def twiny(self):
4635+
def twiny(self, **kwargs):
46314636
"""
46324637
Create a twin Axes sharing the yaxis.
46334638
@@ -4637,6 +4642,11 @@ def twiny(self):
46374642
To ensure that the tick marks of both x-axes align, see
46384643
`~matplotlib.ticker.LinearLocator`.
46394644
4645+
Parameters
4646+
----------
4647+
kwargs : dict
4648+
The keyword arguments passed to ``add_subplot()`` or ``add_axes()``.
4649+
46404650
Returns
46414651
-------
46424652
Axes
@@ -4647,7 +4657,7 @@ def twiny(self):
46474657
For those who are 'picking' artists while using twiny, pick
46484658
events are only called for the artists in the top-most Axes.
46494659
"""
4650-
ax2 = self._make_twin_axes(sharey=self)
4660+
ax2 = self._make_twin_axes(sharey=self, axes_class=type(self), **kwargs)
46514661
ax2.xaxis.tick_top()
46524662
ax2.xaxis.set_label_position('top')
46534663
ax2.set_autoscaley_on(self.get_autoscaley_on())

lib/matplotlib/axes/_base.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import datetime
44
from collections.abc import Callable, Iterable, Iterator, Sequence
55
from matplotlib import cbook
66
from matplotlib.artist import Artist
7-
from matplotlib.axes import Axes
87
from matplotlib.axis import XAxis, YAxis, Tick
98
from matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent
109
from matplotlib.cbook import CallbackRegistry
@@ -29,6 +28,7 @@ import numpy as np
2928
from numpy.typing import ArrayLike
3029
from typing import Any, Literal, TypeVar, overload
3130
from matplotlib.typing import ColorType
31+
from typing_extensions import Self
3232

3333
_T = TypeVar("_T", bound=Artist)
3434

@@ -385,8 +385,8 @@ class _AxesBase(martist.Artist):
385385
bbox_extra_artists: Sequence[Artist] | None = ...,
386386
for_layout_only: bool = ...
387387
) -> Bbox | None: ...
388-
def twinx(self) -> Axes: ...
389-
def twiny(self) -> Axes: ...
388+
def twinx(self, **kwargs) -> Self: ...
389+
def twiny(self, **kwargs) -> Self: ...
390390
def get_shared_x_axes(self) -> cbook.GrouperView: ...
391391
def get_shared_y_axes(self) -> cbook.GrouperView: ...
392392
def label_outer(self, remove_inner_ticks: bool = ...) -> None: ...

lib/matplotlib/tests/test_axes.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7532,6 +7532,28 @@ def test_twinx_knows_limits():
75327532
assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx)
75337533

75347534

7535+
class SubclassAxes(Axes):
7536+
def __init__(self, *args, foo, **kwargs):
7537+
super().__init__(*args, **kwargs)
7538+
self.foo = foo
7539+
7540+
7541+
@pytest.mark.parametrize(("axes_class", "kw0", "kw1"), [
7542+
(Axes, {}, {}),
7543+
(SubclassAxes, {"foo": 0}, {"foo": 1}),
7544+
])
7545+
def test_twinx_subclass(axes_class, kw0, kw1):
7546+
fig = plt.figure()
7547+
classed_ax = fig.add_subplot(axes_class=axes_class, **kw0)
7548+
for k, v in kw0.items():
7549+
assert getattr(classed_ax, k) == v
7550+
7551+
twin = classed_ax.twinx(**kw1)
7552+
assert type(twin) is axes_class
7553+
for k, v in kw1.items():
7554+
assert getattr(twin, k) == v
7555+
7556+
75357557
def test_zero_linewidth():
75367558
# Check that setting a zero linewidth doesn't error
75377559
plt.plot([0, 1], [0, 1], ls='--', lw=0)

0 commit comments

Comments
 (0)