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

3

我目前使用下面的代码块解决了我的问题。它能够实现我的需求,但是有很多重复的代码,并且有些难以阅读。

我需要创建几个图表,并用在一个大的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()也很好。

2个回答

1
为了在代码的不同点操作不同的图形,最好保留所有图形的引用。同时,保留相应轴的引用也是有用的,以便能够绘制到它们上面。
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

1
将您的数字列成一个列表,并按照它们的编号进行导航:
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(figures[0])


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接