3

我有这个简单的代码,它在两个不同的数字(图 1 和图 2)中绘制完全相同的东西。但是,我必须写两次 ax?.plot(x, y) 行,一次用于 ax1,一次用于 ax2。我怎么能只有一个情节表达式(有多个冗余的可能是我更复杂的代码的麻烦来源)。像 ax1,ax2.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()
4

2 回答 2

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)
于 2013-02-15T19:50:36.840 回答
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)

然后,您可以根据需要添加任意数量,并且每个都会发生相同的事情。

于 2013-02-15T19:50:46.990 回答