Python matplotlib - updating data during animation in Conway Game of Life

The code below creates the animation for Conway Game of Life using Python and matplotlib.

I'm not sure why I should do this:

grid = newGrid.copy() mat.set_data(grid) 

Instead simply:

 mat.set_data(newGrid) 

How to update an array associated with a chart without the above copy?

 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation N = 100 ON = 255 OFF = 0 vals = [ON, OFF] # populate grid with random on/off - more off than on grid = np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N) def update(data): global grid newGrid = grid.copy() for i in range(N): for j in range(N): total = (grid[i, (j-1)%N] + grid[i, (j+1)%N] + grid[(i-1)%N, j] + grid[(i+1)%N, j] + grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] + grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255 if grid[i, j] == ON: if (total < 2) or (total > 3): newGrid[i, j] = OFF else: if total == 3: newGrid[i, j] = ON grid = newGrid.copy() mat.set_data(grid) return mat fig, ax = plt.subplots() mat = ax.matshow(grid) ani = animation.FuncAnimation(fig, update, interval=50, save_count=50) plt.show() 

The result seems correct - I see gliders and other expected patterns:

Conway's Game of Life using Python / matplotlib

+4
source share
1 answer

There is no particular reason mat.set_data() needs a copy of newGrid - it is important that the global grid updated from iteration to iteration:

 def update(data): global grid newGrid = grid.copy() """ do your updating. this needs to be done on a copy of 'grid' because you are updating element-by-element, and updates to previous rows/columns will affect the result at 'grid[i,j]' if you don't use a copy """ # you do need to update the global 'grid' otherwise the simulation will # not progress, but there no need to copy() mat.set_data(newGrid) grid = newGrid # # there no reason why you couldn't do it in the opposite order # grid = newGrid # mat.set_data(grid) # at least in my version of matplotlib (1.2.1), the animation function must # return an iterable containing the updated artists, ie 'mat,' or '[mat]', # not 'mat' return [mat] 

Also, in FuncAnimation I would recommend passing blit=True so that you don't redraw the background in every frame.

+2
source

Source: https://habr.com/ru/post/1487424/


All Articles