Python 如何管理多个matplotlib图形的创建、添加数据和显示?

Python 如何管理多个matplotlib图形的创建、添加数据和显示?,python,matplotlib,Python,Matplotlib,我目前已经用下面的代码块解决了我的问题。它做了我想要的,但是有很多代码重复,而且有点难读 我有几个数字,我想创建和填充的数据是在一个大的for循环计算 我很难理解在代码顶部创建和设置标题/元数据的语法,然后将所有正确的数据添加到代码底部的正确数字中 我有这个: import matplotlib.pyplot as plt import numpy as np figure = plt.figure() plt.title("Figure 1") figure.add_subplot(2,2,1

我目前已经用下面的代码块解决了我的问题。它做了我想要的,但是有很多代码重复,而且有点难读

我有几个数字,我想创建和填充的数据是在一个大的for循环计算

我很难理解在代码顶部创建和设置标题/元数据的语法,然后将所有正确的数据添加到代码底部的正确数字中

我有这个:

import matplotlib.pyplot as plt
import numpy as np
figure = plt.figure()
plt.title("Figure 1")
figure.add_subplot(2,2,1)
plt.imshow(np.zeros((2,2)))
# Some logic in a for loop to add subplots
plt.show()

figure = plt.figure()
plt.title("Figure 2")
figure.add_subplot(2,2,1)
# Some Logic in an identical for loop to add different subplots
plt.imshow(np.zeros((2,2)))
plt.show()
我想要更像这样的东西:

# Define variables, titles, formatting, etc.
figure = plt.figure()
figure2 = plt.figure()
figure1.title = "Figure 1"
figure2.title = "Figure 2"

# Populate
figure.add_subplot(2,2,1)
figure2.add_subplot(2,2,1)
# Some logic in a for loop to add subplots to both figures
是否有一种干净的方法来实现我对matplotlib的要求?我主要希望清理一下我的代码,并有一个更容易扩展和维护的程序


我真的只想找到一种方法来定义我所有的人物,在一个地方有标题,然后根据其他逻辑将图像添加到正确的人物中。能够为特定图形调用plt.show()也很好。

为了在代码中的不同点操作不同的图形,最简单的方法是保留对所有图形的引用。此外,保持对各个轴的引用对于能够绘制到这些轴非常有用

import matplotlib.pyplot as plt

figure = plt.figure(1)
figure2 = plt.figure(2)
figure.title("Figure 1")
figure2.title("Figure 2")

ax1 = figure.add_subplot(2,2,1)
ax2 = figure2.add_subplot(2,2,1)
ax999 = figure2.add_subplot(2,2,4)

ax1.plot([2,4,1])
ax2.plot([3,0,3])
ax999.plot([2,3,1])

plt.show()
应始终在末尾调用plt.show()。然后,它将绘制所有打开的图形。要仅显示部分图形,需要编写一个自定义的
show
函数。此函数只需在调用
plt.show
之前关闭所有不需要的数字

import matplotlib.pyplot as plt

def show(fignums):
    if isinstance(fignums, int):
        fignums = [fignums]
    allfigs = plt.get_fignums()
    for f in allfigs:
        if f not in fignums:
            plt.close(f)
    plt.show()


figure = plt.figure(1)
figure2 = plt.figure(2)
figure.title("Figure 1")
figure2.title("Figure 2")

ax1 = figure.add_subplot(2,2,1)
ax2 = figure2.add_subplot(2,2,1)

ax1.plot([2,4,1])
ax2.plot([3,0,3])

show([1, 2])
调用
show
的可能(互斥)方式现在是

show(1) # only show figure 1
show(2) # only show figure 2
show([1,2]) # show both figures
show([]) # don't show any figure

请注意,您仍然可以在脚本末尾仅调用一次
show

将您的数字放入列表,并按其编号在其上导航:

import matplotlib.pyplot as plt
import numpy as np

# data
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)

# set up figures
figures = []
for ind in xrange(1,4):
   f = plt.figure()
   figures.append(f) 
   f.title = "Figure {0:02d}".format(ind)

# Populate with subplots
figures[0].add_subplot(2,2,1)
figures[1].add_subplot(2,2,1)

# select first figure
plt.figure(1) 
# get current axis
ax = plt.gca()
ax.plot(t, s2, 's')

# select 3rd figure
plt.figure(3) 
ax = plt.gca()
ax.plot(t, s1, 's')

plt.show()
如果需要,可以在第一个循环中绘图。 要关闭图形,请使用
plt.close(图形[0])