I’m trying to update a plot dynamically within a for loop and I can’t get it to work. I wonder if anyone can help?
I get a bit confused between passing the figure vs axes and how to update. I’ve been trying to use
display.clear_output(wait=True)
display.display(plt.gcf())
time.sleep(2)
but it’s not doing what I want it to.
I'm trying to: 1. add objects to a grid (setupGrid2) 2. at a timestep - move each object in random direction (makeMove2) 3. update the position of each object visually on the grid (updateGrid2)
My problem is with 3. I'd like to clear the previous step, so that just the new location for each object is displayed. The goal to show the objects dynamically moving around the grid.
I'd also like to work with the ax object created in setupGrid2, so that I can set the plot variables (title, legend etc.) in one place and update that chart.
Grateful for any help.
Sample code below (for running in jupyter notebook):
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import time
import pylab as pl
from IPython import display
def setupGrid2(norows,nocols,noobjects):
#each object needs current grid position (x and y coordinate)
objects = np.zeros(noobjects)
ObjectPos = np.zeros(shape=(noobjects,2))
#put objects randomly on grid
for i in range (noobjects):
ObjectPos[i][0] = np.random.uniform(0,norows)
ObjectPos[i][1] = np.random.uniform(0,nocols)
#plot objects on grid
fig = plt.figure(1,figsize=(15,5))
ax = fig.add_subplot(1,1,1)
x,y = zip(*ObjectPos)
ax.scatter(x, y,c="b", label='Initial positions')
ax.grid()
plt.show()
return ax,ObjectPos
def updateGrid2(ax,ObjPos):
x,y = zip(*ObjPos)
plt.scatter(x, y)
display.clear_output(wait=True)
display.display(plt.gcf())
time.sleep(0.1)
#move object in a random direction
def makeMove2(object,xpos,ypos):
#gets a number: 1,2,3 or 4
direction = int(np.random.uniform(1,4))
if (direction == 1):
ypos = ypos+1
if (direction == 2):
ypos = ypos - 1
if (direction == 3):
xpos = xpos+1
if (direction == 4):
xpos = xpos-1
return xpos,ypos
def Simulation2(rows,cols,objects,steps):
ax,ObjPos = setupGrid2(rows,cols,objects)
for i in range(steps):
for j in range (objects):
xpos = ObjPos[j][0]
ypos = ObjPos[j][1]
newxpos,newypos = makeMove2(j,xpos,ypos)
ObjPos[j][0] = newxpos
ObjPos[j][1] = newypos
updateGrid2(ax,ObjPos)
Simulation2(20,20,2,20)