Skip to content

[Bug]: Axes.cla() resets axis label position of twin axes #28846

Closed as duplicate

Description

@StefRe

Bug summary

I'm making many plots in a loop using the same Figure and Axes. The basic setup including a twin Axes is done once and the Axes are cleared at the end of the loop using cla().

Axes.cla() resets the label position of the yaxis of the twin Axes to the default (left), resulting in misplaced ylabels in all but the first loops.

Ticks and tick labels of the left y axis are kept at the correct side, so I would the axis label also expect to be kept at the correct side.

Code for reproduction

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
for i in range(2):
    # do some plotting here
    ax2.set(ylabel=f'ylabel of plot # {i}', ylim=(1, i + 2))
    fig.savefig(f'{i}.png')
    ax1.cla()
    ax2.cla()

Actual outcome

1.png:

1

Expected outcome

The expected outcome was produced by adding ax2.yaxis.set_label_position('right') to the loop:

1

Additional information

No response

Operating system

No response

Matplotlib Version

3.9.2

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

None

Activity

  1. StefRe commented on Sep 19, 2024

    @StefRe
    ContributorAuthor

    I guess an straightforward fix would be to restore the label position after clearing the axis:

    for axis in self._axis_map.values():
    axis.clear() # Also resets the scale to linear.

    by changing line 1274 to

    old_label_position = axis.label_position
    axis.clear()
    axis.label_position = old_label_position
  2. StefRe commented on Sep 19, 2024

    @StefRe
    ContributorAuthor

    or better do it in Axis.clear() around:

    self._init()

  3. timhoffm commented on Sep 19, 2024

    @timhoffm
    Member

    Semi-related: #27825 and the associated PR #28101

  4. StefRe commented on Sep 20, 2024

    @StefRe
    ContributorAuthor

    the same pertains to the offset position - it's also reset to the left when clearing a twin x-Axes, which is even more misleading because this error is more difficult to spot:

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax2.cla()
    ax2.set_ylim(1e8, 1e8 + 1)

    grafik

  5. timhoffm commented on Sep 20, 2024

    @timhoffm
    Member

    I think this is a duplicate of #28268.

    General note: We currently do not have a clear definition (or even implementation) of the semantics of clear. What parts should be reset and what not? See #28851.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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