2013-02-15 67 views
3

我有这个简单的代码,它在两个不同的图形(图1和图2)中绘制完全相同的图形。然而,我必须写两行ax?.plot(x,y),一次写ax1,一次写ax2。我怎么能只有一个情节表达(有多个redondant可能是我更复杂的代码的麻烦来源)。有点像ax1,ax2.plot(x,y)...?Matplotlib:在两个不同的图形中绘制相同的图形,而不写入“plot(x,y)”线两次

import numpy as np 
import matplotlib.pyplot as plt 

#Prepares the data 
x = np.arange(5) 
y = np.exp(x) 

#plot fig1 
fig1 = plt.figure() 
ax1 = fig1.add_subplot(111) 

#plot fig2 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111) 

#adds the same fig2 plot on fig1 
ax1.plot(x, y) 
ax2.plot(x, y) 

plt.show() 

回答

1

您可以每个轴添加到列表中,这样的:

import numpy as np 
import matplotlib.pyplot as plt 

axes_lst = []  
#Prepares the data 
x = np.arange(5) 
y = np.exp(x) 


#plot fig1 
fig1 = plt.figure() 
ax1 = fig1.add_subplot(111) 
axes_lst.append(ax1) 

#plot fig2 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111) 
axes_lst.append(ax2) 

for ax in axes_lst: 
    ax.plot(x, y) 

plt.show() 

,或者您可以使用此功能不支持拉所有的图中pyplot。 (?)从https://stackoverflow.com/a/3783303/1269969

figures=[manager.canvas.figure 
     for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] 
for figure in figures: 
    figure.gca().plot(x,y) 
+0

我不知道我能做到这一点。非常感谢! – user2076688 2013-02-15 20:10:10

+0

如果你正在谈论第二种方法,请记住,没有人会认为这将在未来的版本中起作用。 __pylab_helpers表明它应该是私人的,所以你不能总是依靠它工作。 – placeybordeaux 2013-02-15 20:29:58

+0

我会强烈建议你为列表和循环变量选择不影响'pyplot'函数的不同名称。此外,你的第二个例子不起作用,你需要做'figure.gca()。plot(x,y)'并且将绘制成_every_开放图,而不仅仅是你想要的两个。 – tacaswell 2013-02-15 21:01:32

1

拍摄,而无需了解matplotlib,你可以所有的轴添加到列表:

to_plot = [] 
to_plot.append(ax1) 
... 
to_plot.append(ax2) 
... 

# apply the same action to each ax 
for ax in to_plot: 
    ax.plot(x, y) 

然后,您可以添加多达你喜欢,同样的事情也会发生在每个。

+0

我不知道我能做到这一点。非常感谢! – user2076688 2013-02-15 20:10:28

相关问题