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

Skip to content

FIX: removing colorbar's axes also removes colorbar#31555

Open
rcomer wants to merge 1 commit intomatplotlib:mainfrom
rcomer:cbar-axes
Open

FIX: removing colorbar's axes also removes colorbar#31555
rcomer wants to merge 1 commit intomatplotlib:mainfrom
rcomer:cbar-axes

Conversation

@rcomer
Copy link
Copy Markdown
Member

@rcomer rcomer commented Apr 23, 2026

PR summary

Closes #31330

Replace the colorbar axes's remove method so it calls the colorbar's own remove method. The code from the issue now gives me a plot. I also thought about having the axes remove method raise an exception with a message to use the colorbar's method instead. However, I think either way we'd need to replace the method and it's no bigger change to support it than to make it raise.

This is an alternative solution to #31549, which was opened first.

AI Disclosure

None

PR checklist

Copy link
Copy Markdown
Member

@jklymak jklymak left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me!

Comment thread lib/matplotlib/colorbar.py
Comment on lines +439 to +441
# Override axes' remove method to properly remove the colorbar
self._ax_remove = self.ax._remove_method
self.ax._remove_method = functools.partial(_remove_cbar_axes, cbar=self)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# Override axes' remove method to properly remove the colorbar
self._ax_remove = self.ax._remove_method
self.ax._remove_method = functools.partial(_remove_cbar_axes, cbar=self)
# Ensure proper cleanup also when `cbar.ax.remove()` is called. We ensure
# this by overriding the Axes' remove method, so that `cbar.ax.remove()`
# actually calls`cbar.remove()`. In turn, we store the original Axes' remove
# method in `_ax_remove`, which `cbar.remove()` will eventually call to
# clean up the Axes itself.
self._ax_remove = self.ax._remove_method
self.ax._remove_method = lambda self_: self.remove()

This warrants a bit more explanation - at least I had some trouble understanding how this works. Also, You can get away with a lambda and don't need an extra _remove_cbar_axes

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Crash when removing colorbar axes in a constrained layout

3 participants