matplotlib-循环实时更新图形的问题

matplotlib-problem with real-time update of figure in a loop

我想绘制 4 个颜色随机变为白色或红色的方块。然而,当我如下编码时,之前的颜色保持不变,直到所有四个块都变成红色。

from numpy import random, round
from matplotlib.pyplot import figure, show, \
     close, clf, cla, ion, ioff, pause


LDX = [100, 100, 150, 150]
LDY = [50, 100, 50, 100]

fig = figure()
ax = fig.add_axes([0.125, 0.1, 0.7, 0.8])
ion()
for ii in range(100):
    randperm = round(random.rand(len(LDX)))
    for i in range(len(LDX)):
        ldx = LDX[i]
        ldy = LDY[i]    
        h11, = ax.plot(
            [ldx-25, ldx+25, ldx+25,
             ldx-25, ldx-25], 
            [ldy+25, ldy+25, ldy-25,
             ldy-25, ldy+25],
            color='k')    
    for i in range(len(LDX)):
        if randperm[i]==1:
            ldx = LDX[i]
            ldy = LDY[i]
            h12, = ax.fill(
                [ldx-25, ldx+25, ldx+25,
                 ldx-25, ldx-25], 
                [ldy+25, ldy+25, ldy-25,
                 ldy-25, ldy+25],
                color='r')
    fig.show()
    fig.canvas.draw()
    fig.canvas.flush_events()
    pause(0.001)

通过对您提供的代码进行一些小的修改,您可以获得所需的结果。

from numpy import random, round
from matplotlib.pyplot import figure, show, \
    close, clf, cla, ion, ioff, pause

for j in range(100):
    LDX = [100, 100, 150, 150]
    LDY = [50, 100, 50, 100]
    fig = figure()
    ax = fig.add_axes([0.125, 0.1, 0.7, 0.8])
    randperm = round(random.rand(len(LDX)))

    for i in range(len(LDX)):
        ldx = LDX[i]
        ldy = LDY[i]    
        h11, = ax.plot(
            [ldx-25, ldx+25, ldx+25,
            ldx-25, ldx-25], 
            [ldy+25, ldy+25, ldy-25,
            ldy-25, ldy+25],
            color='k')
    for i in range(len(LDX)):
        if randperm[i]==1:
            ldx = LDX[i]
            ldy = LDY[i]
            h12, = ax.fill(
                [ldx-25, ldx+25, ldx+25,
                ldx-25, ldx-25], 
                [ldy+25, ldy+25, ldy-25,
                ldy-25, ldy+25],
                color='r')

    show(block=False)
    pause(0.5)

通过@BreandanA 的指导和评论,我找到了如下答案:

ion()
fig = figure()
for j in range(100):
    LDX = [100, 100, 150, 150]
    LDY = [50, 100, 50, 100]
    randperm = round(random.rand(len(LDX)))
    clf()
    ax = fig.add_axes([0.125, 0.1, 0.7, 0.8])
    for i in range(len(LDX)):
        ldx = LDX[i]
        ldy = LDY[i]    
        h11, = ax.plot(
            [ldx-25, ldx+25, ldx+25,
            ldx-25, ldx-25], 
            [ldy+25, ldy+25, ldy-25,
            ldy-25, ldy+25],
            color='k')
    for i in range(len(LDX)):
        if randperm[i]==1:
            ldx = LDX[i]
            ldy = LDY[i]
            h12, = ax.fill(
                [ldx-25, ldx+25, ldx+25,
                ldx-25, ldx-25], 
                [ldy+25, ldy+25, ldy-25,
                ldy-25, ldy+25],
                color='r')
    draw_all()
    pause(0.001)