Skip to content

[ENH]: Give control whether twinx() or twiny() overlays the main axis #31122

@GiusCappelli

Description

@GiusCappelli

Problem

By default, twinx produces an axis that overlays ax.
I routinely find myself wanting to show the twin axis content in the background of the main axis content, and not the other way around.
I think this is natural for a user/reader that looks at figures, because we tend to read from left to right and hence the data of the left y-axis takes precedence (should render in the foreground).

Preferences aside, the workaround is always the same:

...
ax_t = ax.twinx()
# make twinx contents appear in the background of main ax
ax.patch.set_visible(False)
ax.set_zorder(ax_t.get_zorder() + 1)
...

I think ergonomics would increase by an ε if twinx accepted one more overlay boolean argument which decides whether the twinx/y is in the "foreground" or "background" of ax.

Proposed solution

I would modify the definition of _make_twin_axes (https://github.com/matplotlib/matplotlib/blob/v3.10.8/lib/matplotlib/axes/_base.py#L4595) adding a boolean argument overlay=true.

If false, self.patch.set_visible(False) (would this work?) and twin.set_zorder(self.zorder + 1).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions