0

For normal plots, matplotlib can use

data, = plt.plot([], [])

for i in range(n):
   data.set_data(i, i)

and i can continuously update the plot. However I have a grid map which uses imshow instead of plot.

plt.figure(1)
cmap = colors.ListedColormap(['white', 'black'])
bounds = [-0.5,0.5,1.5]
norm = colors.BoundaryNorm(bounds, cmap.N)
plt.show(block=False)

for i in range(n):
   plt.imshow(data, cmap=cmap, norm=norm)    
   plt.draw()

imshow does not seem to have update method since it takes in the whole data. Is there a way I can plot a gridmap shown here with plt? Or is there a way I can update grid map using imshow?

MoneyBall
  • 2,343
  • 5
  • 26
  • 59

1 Answers1

2

imshow returns an AxesImage which also has a set_data method:

# Based on code from https://stackoverflow.com/a/43971236/190597 (umutto) and
# https://stackoverflow.com/q/23042482/190597 (Raphael Kleindienst)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.colors as mcolors
import matplotlib.collections as mcoll

fig, ax = plt.subplots()
cmap = mcolors.ListedColormap(['white', 'black'])
bounds = [-0.5, 0.5, 1.5]
norm = mcolors.BoundaryNorm(bounds, cmap.N)
data = np.random.rand(10, 10) * 2 - 0.5
im = ax.imshow(data, cmap=cmap, norm=norm)

grid = np.arange(-0.5, 11, 1)
xmin, xmax, ymin, ymax = -0.5, 10.5, -0.5, 10.5
lines = ([[(x, y) for y in (ymin, ymax)] for x in grid]
         + [[(x, y) for x in (xmin, xmax)] for y in grid])
grid = mcoll.LineCollection(lines, linestyles='solid', linewidths=2,
                            color='teal')
ax.add_collection(grid)

def animate(i):
    data = np.random.rand(10, 10) * 2 - 0.5
    im.set_data(data)
    # return a list of the artists that need to be redrawn
    return [im, grid]

anim = animation.FuncAnimation(
    fig, animate, frames=200, interval=0, blit=True, repeat=True)
plt.show()

enter image description here

For more on FuncAnimation, see the docs and this tutorial. The matplotlib gallery also has a number of examples of how to use FuncAnimation.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677