Adding the same Patch instance to multiple subnets in matplotlib

I am trying to add the same patch instance to multiple axes in matplotlib. Here is a minimal example:

import matplotlib.pyplot as mpl_plt import matplotlib.patches as mpl_patches fig, (axes_1, axes_2) = mpl_plt.subplots(2,1) axes_1.axis([-5, 5, -5, 5]) axes_2.axis([-5, 5, -5, 5]) # Create ellipse and add it to the axes ellipse = mpl_patches.Ellipse((1,1), 0.5, 0.8) axes_1.add_patch(ellipse) axes_2.add_patch(ellipse) # Change the position of the ellipse ellipse.center = (2,2) # Show the plot mpl_plt.show() 

In this example, the ellipse is not displayed in any subheading. If I comment on the line axes_2.add_patch(ellipse) , the ellipse will appear in the first subheading in its moved location (2,2). Is it possible for an ellipse to appear in several axes and have changes in it, reflected in both?

My ultimate goal is to add artists to different subheadings and have changes to artists reflected in all axes. It would be even better to use zoomed_inset_axes from mpl_toolkits to have a nested graph that shows a close-up of the patch, where changes to the patch will be shown both in the main graph and in the inset.

+7
python matplotlib plot
source share
1 answer

One way to do this is to use the class to set all user preferences for the artist. I made an example class that has a default value for each property. If you then simply make a reference to the artistic function of this class, each time you get a new instance, but with exactly the same parameters. Notice how I changed Ellipse1 to have xy = (2,2), and this appeared on both graphs. Just for added talent, I did this so you can name more than one type of patch using getattr. Does this suggest that there are common arguments for different patches or? You can make it complicated or simple as you like, I suppose.

 import matplotlib.pyplot as mpl_plt import matplotlib.patches as mpl_patches class artist_instance: def __init__(self, xy=None, width=None, height=None, type=None, ): self.xy=xy if xy is not None else (1,1) self.width=width if width is not None else 0.5 self.height=height if height is not None else 0.8 self.type=type if type is not None else 'Ellipse' def art(self): return getattr(mpl_patches,self.type)(xy=self.xy,width=self.width,height=self.height) Ellipse1=artist_instance(xy=(2,2)) fig, (axes_1, axes_2) = mpl_plt.subplots(2,1) axes_1.axis([-5, 5, -5, 5]) axes_2.axis([-5, 5, -5, 5]) axes_1.add_patch(Ellipse1.art()) axes_2.add_patch(Ellipse1.art()) mpl_plt.show() 

Graph result

0
source share

All Articles