Matplotlib:在两个不同图形中绘制相同图,不重复写“plot(x,y)”

3 投票
2 回答
3177 浏览
提问于 2025-04-17 16:02

我有一段简单的代码,它在两个不同的图形(fig1和fig2)中画出完全相同的内容。不过,我需要把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()

2 个回答

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)

这样你就可以添加任意数量的坐标轴,所有的坐标轴都会做同样的事情。

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)

撰写回答