【问题标题】:Plot of a changing matrix ... gone wrong不断变化的矩阵图...出错了
【发布时间】:2021-12-30 15:36:01
【问题描述】:

我正在尝试在 Python 中绘制一个矩阵。所以,我最初的想法是使用 matshow。

但是,这个特定的矩阵通过算法(下面的函数 sandpile)随着时间的推移而发展,所以我需要展示矩阵如何随着时间的推移而发展 - 但在同一个图中。最终结果是一种动画。关于如何完成的任何想法?下面的代码只生成一个图,那是最近更新的矩阵的图片(下面称为 abba 的矩阵)。

提前谢谢你。

import numpy as np
import matplotlib.pyplot as plt

dimension = 3
abba = np.matrix( [ [2,5,2], [1,1000,4], [2,1,2] ] )

def sandpile(field):

    greater3 = np.where(field > 3)
    
    left = (greater3[0], greater3[1]-1)
    right = (greater3[0], greater3[1]+1)
    top = (greater3[0] - 1, greater3[1])
    bottom = (greater3[0]+1 , greater3[1])

    bleft   = left[0][np.where(left[1] >= 0)], left[1][np.where(left[1] >= 0)]
    bright  = right[0][np.where(right[1] < dimension)], right[1][np.where(right[1] < dimension)]
    btop    = top[0][np.where(top[0] >= 0)], top[1][np.where(top[0] >= 0)]
    bbottom = bottom[0][np.where(bottom[0] < dimension)], bottom[1][np.where(bottom[0] < dimension)]

    field[greater3] -= 4

    field[bleft] += 1
    field[bright] += 1
    field[btop] += 1
    field[bbottom] += 1
            
    return (field) 

print(abba)

matfig = plt.figure(figsize=(3,3))
plt.matshow(abba, fignum=matfig.number)

n = 0
while (abba < 4).all() == False:
    
    abba = sandpile(abba)
    
    plt.matshow(abba, fignum=matfig.number)
    
    n += 1

print('Exit with',n,'steps')
print(abba)

【问题讨论】:

    标签: python matplotlib matrix


    【解决方案1】:

    这是您可以在循环中查看更新图的一种方式:

    ...
    
    matfig = plt.figure(figsize=(3,3))
    ax1 = matfig.add_subplot(1, 1, 1)
    ax_image = ax1.imshow(abba)
    plt.show(block=False)
    
    n = 0
    while (abba < 4).all() == False:
    
        abba = sandpile(abba)
    
        ax_image.remove()
        ax_image = ax1.imshow(abba)
        matfig.canvas.draw()
        matfig.canvas.flush_events()
        n += 1
        print(n)
    
    print('Exit with',n,'steps')
    print(abba)
    plt.show(block=True)
    

    在您的示例中,更改发生在循环的最后。

    【讨论】:

    • 感谢您发布 Mehdi - 我尝试了您的建议,但屏幕上仍然只有一张照片。
    • 您的意思是您可以看到情节已更新但在一个图形/窗口中?对吗?
    • 很遗憾,我只看到一张静态图片 - 我没有看到任何更新,只有同一张图片。
    • 特曼,你等得够久了吗?使用您的样本输入,一段时间内没有太大变化,然后突然间一切都发生在最后一秒。从 100 而不是 1000 开始,并在循环末尾添加 plt.pause(0.1)。说了这么多,matplotlib交互模式高度依赖你使用的操作系统和IDE,资料,我们没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2019-02-20
    • 2021-02-15
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多