绘制多个持久图

时间:2017-08-10 12:18:14

标签: python matplotlib

我想展示两张图,这些图由我的程序不断更新。但是,我尝试的解决方案只能显示两个图形中的第二个,而第一个图形只显示为空白窗口。

这是我的代码:

def show1(x, y):
    fig = plt.figure(1)
    fig.canvas.set_window_title("Plot1")
    plt.plot(x, y)
    plt.pause(0.01)
    plt.show()
    plt.figure(1).clear()

def show2(x, y):
    fig = plt.figure(2)
    fig.canvas.set_window_title("Plot2")
    plt.plot(x, y)
    plt.pause(0.01)
    plt.show()
    plt.figure(2).clear()

plt.ion()
x = [1, 2, 3, 4]
i = 0

while True:
    y1 = [j + i for j in x]
    show1(x, y1)
    y2 = [j + 2 * i for j in x]
    show2(x, y2)
    time.sleep(2)
    i += 1

因此,在循环的每次迭代中,将更新要绘制的值,并重新绘制图形。在绘制每个图形之后,我调用plt.figure(k).clear()来清除图形k,这样下次我写入图形时,我将在空白画布上书写(而不是将多个图形连续添加到相同的图形中)图)。

但是会发生什么事,我看到第一张图显示了它的图,但是一旦第二张图被绘制出来,第一张图就变成了一个空白窗口,只有第二张图实际上仍然显示其显示的图

如何修改我的代码,以便两个图表都有持久显示?

1 个答案:

答案 0 :(得分:1)

我希望这就是你想要的。

import matplotlib.pyplot as plt
import time

fig1, ax1 = plt.subplots()
fig1.canvas.set_window_title("Plot1")

fig2, ax2 = plt.subplots()
fig2.canvas.set_window_title("Plot2")

x = [1, 2, 3, 4]
i = 0
# initial plots, so Lines objects exist
line1, = ax1.plot(x, [j + i for j in x])
line2, = ax2.plot(x, [j + 2 * i for j in x])

def show1(y):
    line1.set_ydata(y)  # update data, i.e. update Lines object
    ax1.relim()  # rescale limits of axes
    ax1.autoscale_view()  # rescale limits of axes
    fig1.canvas.draw()  # update figure because Lines object has changed

def show2(y):
    line2.set_ydata(y)
    ax2.relim()
    ax2.autoscale_view()
    fig2.canvas.draw()

while True:
    y1 = [j + i for j in x]
    show1(y1)
    y2 = [j + 2 * i for j in x]
    show2(y2)
    time.sleep(2)
    i += 1

不要一遍又一遍地清除图形,只需更新图形(即Lines对象)。这可能是有用的,例如当包含Slider时(参见here,部分代码来自此matplotlib示例)。

相关问题