python - 如何在 ArtistAnimation 中显示更改子图标签 (plt.text) 的进度以及颜色变化

标签 python matplotlib animation python-3.9 matplotlib-animation

运行 python 3.9:

import matplotlib.pyplot as plot
import numpy as np
import matplotlib.animation as animation

fig, plt = plot.subplots()

myArray = np.array([[0,  1,  2,   3,  4,  5,  6],
                    [7,  8,  9,  10, 11, 12, 13],
                    [14, 15, 16, 17, 18, 19, 20],
                    [21, 22, 23, 24, 25, 26, 27],
                    [28, 29, 30, 31, 32, 33, 34],
                    [35, 36, 37, 38, 39, 40, 41],
                    [42, 43, 44, 45, 46, 47, 48]])
def randint():
    return np.random.randint(0, 7)

def randNewValue():
    return np.random.randint(0, 48) #/10

def labelSquares():
    for i in range(7):
        for j in range(7):
            plt.text(j, i, myArray[i, j], ha="center", va="center", color="white")

def modifyArrayElement(r, c, x):
    row = r
    col = c
    new_value = x
    myArray[row, col] = new_value
    # labelSquares()
    return myArray

ims = []

for i in range(100):
    row = randint()
    col = randint()
    newValue = randNewValue()
    # plt.text(col, row, myArray[row, col], ha="center", va="center", color="white")
    # labelSquares()
    im = plt.imshow(modifyArrayElement(row, col, newValue), animated = True)
    if i == 0:
        plt.imshow(modifyArrayElement(row, col, newValue))
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval = 400, blit = True, repeat_delay = 5000)


labelSquares() # how to make it run "during" the animation, i.e: show progression of changing labels (plt.text) along with color changing, matching myArray values at each iteration?
f = r"c://Temp/animation.gif"
writergif = animation.PillowWriter(fps=2)
# ani.save(f, writer=writergif)
plot.show()

结果显示随着 myArray 内容的变化而改变正方形颜色的动画,但是,我希望其中的数字(文本标签)也随之变化,在 for 循环的每次迭代中匹配 myArray 值,而不是停留在始终保持最终值静态。将 labelSquares() - 或任何类似的标记尝试放在 for 循环内 - 不起作用。有办法做到吗? (抱歉,如果这是一个小问题,表明我对 pyplot 缺乏经验,我希望所有专家原谅我问这样一个愚蠢的问题)

animation result

最佳答案

来自ArtistAnimation documentationartiSTList 参数上:

Each list entry is a collection of Artist objects that are made visible on the corresponding frame.

请注意,您添加到 Matplotlib 图窗的每个对象都是一位艺术家,包括由 plt.text 返回的 Text 对象。因此,对于每一帧,我们都可以获取这些并将它们与来自 imshowAxesImage 艺术家一起放入一个列表中。

由于您的 ModifyArrayElement 函数就地更改了全局数组,因此 labelSquares 函数会自动进行这些更新,imshow 也是如此,因此我简化了 imshow 调用。还在 plt.text 中添加了 animated=True 以防止不必要的绘制。

import matplotlib.pyplot as plot
import numpy as np
import matplotlib.animation as animation

fig, plt = plot.subplots()

myArray = np.array([[0,  1,  2,   3,  4,  5,  6],
                    [7,  8,  9,  10, 11, 12, 13],
                    [14, 15, 16, 17, 18, 19, 20],
                    [21, 22, 23, 24, 25, 26, 27],
                    [28, 29, 30, 31, 32, 33, 34],
                    [35, 36, 37, 38, 39, 40, 41],
                    [42, 43, 44, 45, 46, 47, 48]])
def randint():
    return np.random.randint(0, 7)

def randNewValue():
    return np.random.randint(0, 48) #/10

def labelSquares():
    all_texts = []
    for i in range(7):
        for j in range(7):
            all_texts.append(plt.text(j, i, myArray[i, j], ha="center",
                                      va="center", color="white",
                                      animated=True))
    return all_texts
            

def modifyArrayElement(r, c, x):
    row = r
    col = c
    new_value = x
    myArray[row, col] = new_value
    return myArray

artists = []

for i in range(100):
    row = randint()
    col = randint()
    newValue = randNewValue()
    modifyArrayElement(row, col, newValue)
    im = plt.imshow(myArray, animated=True)
    frame_artists = labelSquares()
    frame_artists.append(im)
    artists.append(frame_artists)

ani = animation.ArtistAnimation(fig, artists, interval = 400, blit = True, repeat_delay = 5000)


writergif = animation.PillowWriter(fps=2)
ani.save("myanim.gif", writer=writergif)

enter image description here

关于python - 如何在 ArtistAnimation 中显示更改子图标签 (plt.text) 的进度以及颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77736673/

相关文章:

macos - 太阳经过天空仅需10小时

python - scrapy蜘蛛绕过拒绝我的规则

python - 如何在 Pandas 中高效处理时间序列数据

matplotlib - Julia PyPlot 无法创建二次函数

python - matplotlib plt.show() 仅选择对象

iphone - 显示 CALayer 动画的帧速率 (FPS)

javascript - Raphael 中的动画是如何完成的?

python - 使用redis_om(python)覆盖redis上的信息

python - 用scrapy下载整页

pandas - 在 pandas 中绘制总和和平均值时出现错误