0

I am plotting data with matplotlib.

I would like to watch the data being plotted over a few seconds time.

Current script (below) is close.. It closes the existing plot and makes a new plot including one additional data point for each while loop iteration.

If the "fig=" and "ax1=" statements are instead typed above the loop, I get only a blank plot.

import numpy as np
import matplotlib.pyplot as plt 
import numpy as np
import time
#import matplotlib.animation as animation


def animate2(i):

    k=1

    #fig=plt.figure()
    #ax1=fig.add_subplot(1, 1, 1)

    while k <=len(i):

        fig=plt.figure()
        ax1=fig.add_subplot(1, 1, 1)

        ax1.clear
        ax1.plot(i[0:k, 0], i[0:k, 1])

        plt.show()
        time.sleep(1)
        k=k+1

Here the a sample np array I've used:

test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])

animate2(test_data)

Also, if you think matplotlib.animation would work better, please provide an example!

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
user80112
  • 61
  • 1
  • 2
  • 10

1 Answers1

0

Using matplot.animation. It uses interval=miliseconds instead of time.sleep(). repeat stops looping. frames can be integer (number of frames) or list with numbers - every element from list is send to function as argument i.

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.animation as animation


def animate2(i):

    ax1.clear()
    ax1.plot(test_data[0:i, 0], test_data[0:i, 1])

# ---

test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

# create animation
animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)

# start animation
plt.show()

You can also use fargs=tuplet-with-arguments to send own arguments to function

def animate2(i, data):

    ax1.clear()
    ax1.plot(data[0:i, 0], data[0:i, 1])

# ---

animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), 
                         fargs=(test_data, ), interval=1000)

EDIT:

I used this code to generate animated GIF

(it needs imagemagick installed: https://stackoverflow.com/a/25143651/1832058)

# create animation
ani = animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)

# save animation
ani.save('animation.gif', writer='imagemagick', fps=1)

and got this result

enter image description here

Community
  • 1
  • 1
furas
  • 134,197
  • 12
  • 106
  • 148