Skip to content Skip to sidebar Skip to footer

Python, Matplotlib, Plot Multi-lines (array) And Animation

I'm starting programming in Python (and OOP), but I have a solid experience in Fortran (90/95) and Matlab programming. I'm developing a little tool using animation on tkinter envir

Solution 1:

as @Rutger Kassies points out in the comments,

dline = plot(xx,data)

does some magic parsing on the input data, separates your arrays into a bunch of x-y pairs and plots those. Note that dline is a list of Line2D objects. In this case

mline, = plot([],[])
mline.set_data(xx.T,data.T)

you are creating a single Line2D object and the library does it's best to shove 2D data, into a 1D plotting objects and does so by flattening the input.

To animate N lines, you just need NLine2D objects:

lines = [plot([],[])[0] for j inrange(Ny)] # make a whole bunch of linesdefinit():
    for mline in lines:
        mline.set_data([],[])
    return lines

defanimate(coef):
   data = odata * (1.-float(coef)/360.)
   for mline, x, d inzip(lines, data.T, xx.T):
       mline.set_data(x, d)
   return lines

You also don't need to pre-allocate data and doing the loops in python is much slower than letting numpy do them for you.

Solution 2:

Many thanks to Rutger Kassies and tcaswell. Here the same example as above but now it works as I want. I hope that it will help another python programmers.

from pylab import *
from matplotlib import animation

Nx=10
Ny=20

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)
axis([0, Nx-1, 0, Ny])

xx    = zeros( ( Nx,Ny) )
data  = zeros( ( Nx,Ny) )
odata = zeros( ( Nx,Ny) )

for ii inrange(0,Nx):
    xx[ii,:]    = float(ii)

for jj inrange(0,Ny):
    odata[:,jj] = float(jj)

#dline = plot(xx,odata)

lines = [plot([],[])[0] for j inrange(Ny)] # make a whole bunch of linesdefinit():
    for mline in lines:
        mline.set_data([],[])
    return lines

defanimate(coef):

   data = odata * (1.-float(coef)/360.)

   for mline, x, d inzip(lines, xx.T, data.T,):
       mline.set_data(x, d)

   return lines

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=360, 
                               interval=5,
                               blit=True)

plt.show()

Post a Comment for "Python, Matplotlib, Plot Multi-lines (array) And Animation"