如何在Python中将多个图编译成一个图?

Bot*_*ght 5 python plot matplotlib

我目前正在尝试将多个图合并为一个图(带有子图)。请查看以下代码:

import matplotlib.pyplot as plt

a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))

plots = []

plt.plot(a, b)
plots.append(plt.gcf())
plt.close()

plt.plot(a, c)
plots.append(plt.gcf())
plt.close()

plt.plot(b, c)
plots.append(plt.gcf())
plt.close()

plt.plot(a, d)
plots.append(plt.gcf())
plt.close()

fig, ax = plt.subplots(len(plots))
for i,plot_obj in enumerate(plots, start=1):
    print(f"{i=}, {plot_obj=}")
    ax[i].set_figure(plot_obj)
    plot_obj.show()


plt.tight_layout()
plt.show()

# plt.savefig('temp.png')
Run Code Online (Sandbox Code Playgroud)

我的限制是 -

  1. 绘图将在之前创建 - 我将figure对象存储在列表中。
  2. 稍后需要在代码中访问这些图,并且需要创建一个图形,并将每个图作为子图。

RuntimeError: Can not put single artist in more than one figure在运行上面的代码时,我在尝试设置每个子图的数字时遇到了错误。思考过程是用保存的figure对象设置每个子图的图形。有什么办法可以做到这一点吗?

谢谢!

小智 1

这可能不是最简洁的编写方式,但我想它可以满足您的需求:

a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))

plots = []

fig=plt.figure()
plt.plot(a, b)
plots.append(fig)
plt.close()

fig=plt.figure()
plt.plot(a, c)
plots.append(fig)
plt.close()

fig=plt.figure()
ax3= plt.plot(b, c)
plots.append(fig)
plt.close()

fig=plt.figure()
plt.plot(a, d)
plots.append(fig)
plt.close()

fig,axs =plt.subplots(2,2)
axs[0,0].plot(a,b)
axs[0,1].plot(a,c)
axs[1,0].plot(b,c)
axs[1,1].plot(a,d)
plt.tight_layout()

plt.savefig('temp.png')
Run Code Online (Sandbox Code Playgroud)