【发布时间】: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