How to move artists to other axes?

Hi everyone

I tried to move artists (e.g., patches.Circle) to other axes. The test code:

import numpy as np
from matplotlib import patches
from matplotlib import pyplot as plt

data = np.random.rand(5,5)

fig = plt.figure()
ax1, ax2 = fig.subplots(1,2)
ax1.imshow(data, interpolation='nearest', cmap='gray',)
ax2.imshow(data, interpolation='bilinear', cmap='gray',)
if 1:
    art = patches.Circle((2, 2), 2, fill=0)
    ax1.add_artist(art)
    art.remove()
    ax2.add_artist(art)
plt.show()

What I have tried is removing the art from ax1 and adding it back to ax2, but ax2 doesn’t draw the circle. The expected outcome is:
image

What’s wrong with my code?
Thank you in advance!

EDIT
I found that the art doesn’t seem to be completely removed from ax1…
Tested with matplotlib 3.6.3/TkAgg / Python 3.10.8 / Windows 10

AGDRec_20230205_113912.agm_clip_drop

You have to update the transform to match the data coordinates of the new axes:

...
art = patches.Circle((2, 2), 2, fill=0)
ax1.add_artist(art)
art.remove()
art.set_transform(ax2.transData)  # <-- Line added
ax2.add_artist(art)
1 Like

Hi Hannes,
Thank you very much for the great, simple solution!

Additionally, I think that add_artist and remove would be more symmetric if

art._transformSet = False

is added in art.remove().

Thank you!

Can you open an issue or PR to that effect?

Of course! I will open an issue today.

1 Like