如何管理创建,添加数据和显示多个matplotlib数字?

时间:2017-03-13 23:27:50

标签: python matplotlib

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

我想要创建几个数字并填充以大型for循环计算的数据。

我无法找出在我的代码顶部创建和设置titles / meta数据的语法,然后将所有正确的数据添加到我代码底部的正确数字中。

我有这个:

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 个答案:

答案 0 :(得分: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 :(得分: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])