kam*_*mek 7 python plot matplotlib
我试图在matplotlib中向多个轴添加相同的补丁实例.这是最小的例子:
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()
Run Code Online (Sandbox Code Playgroud)
在此示例中,椭圆不会出现在任何子图中.如果我注释掉该线axes_2.add_patch(ellipse),则椭圆出现在其移动位置的第一个子图中(2,2).是否有可能让椭圆出现在多个轴上并且两者都有变化?
我的最终目标是能够将艺术家添加到不同的子图中,并对所有轴上反映的艺术家进行更改.更好的方法是使用zoomed_inset_axesfrom mpl_toolkits有一个插图,显示补丁的特写,其中补丁的更改将显示在主图和插图中.
实现此目的的一种方法是使用类来设置艺术家的所有自定义设置。我创建了一个示例类,每个属性都有一个默认值。如果您只引用此类的 art 函数,您每次都会获得一个新实例,但参数完全相同。请注意我如何将 Ellipse1 更改为 xy=(2,2) 并显示在两个图上。只是为了增加一点天赋,我这样做了,这样您就可以使用 getattr 调用多个补丁类型。这是假设不同补丁有共享参数还是?我想你可以把它变得复杂或简单。
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()
Run Code Online (Sandbox Code Playgroud)