Python 使用另一个图形的剪辑框保存图形

Python 使用另一个图形的剪辑框保存图形,python,matplotlib,Python,Matplotlib,通常,如果在pyplot中使用默认设置打印两个不同的图形,它们的大小将完全相同,如果保存,则可以在PowerPoint或类似文件中整齐对齐。但是,我想生成一个图形,该图形外部有一个图例。我使用的脚本如下所示 import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,1,201) y1=x**2 y2=np.sin(x) fig1=plt.figure(1) plt.plot(x,y1,label='y1') hand

通常,如果在pyplot中使用默认设置打印两个不同的图形,它们的大小将完全相同,如果保存,则可以在PowerPoint或类似文件中整齐对齐。但是,我想生成一个图形,该图形外部有一个图例。我使用的脚本如下所示

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)

fig1=plt.figure(1)
plt.plot(x,y1,label='y1')
handles1,labels1=plt.gca().get_legend_handles_labels()
lgd1=plt.gca().legend(handles1,labels1,bbox_to_anchor=(1.27,1),borderaxespad=0.)

fig2=plt.figure(2)
plt.plot(x,y2)

fig1.savefig('fig1',bbox_extra_artists=(lgd1,),bbox_inches='tight')
fig2.savefig('fig2')

plt.show()
问题是,在PowerPoint中,我无法再将两个图形左对齐,并使其轴对齐。由于第一个图形使用了“额外艺术家”和“bbox_inches=tight”参数,因此其边距的宽度与第二个图形不同


有没有办法将剪辑框从第一个图形“转移”到第二个图形,这样就可以通过PowerPoint中的“左对齐”来对齐它们?

我认为实现您想要的效果的一个更简单的方法是只构建一个带有两个子图的图形,然后让matplotlib为您对齐所有内容

你认为这样做是个好主意吗

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)

fig = plt.figure()

a = fig.add_subplot(211)

a.plot(x,y1, label='y1')

lgd1 = a.legend(bbox_to_anchor = (1.27,1), borderaxespad=0.)

a = fig.add_subplot(212)
a.plot(x,y2)

fig.savefig('fig',bbox_extra_artists=(lgd1,),bbox_inches='tight')

谢谢约翰;我曾想到用这种方法解决这个问题,但我也希望能够使用单独的数字。我在Matplotlib文档中看到过像“\u get\u clip\u box”和“\u set\u clip\u box”这样的属性(但没有示例或详细描述),因此我认为这应该是可能的。