Plot the last 100 points in matplotlib - python

The following gif is created with gnuplot and Fortran. However, now I want to do the same using only Python (animation form matplotlib mainly).
I can generate a gif with Python but I don't know how to generate something like the righthand side gif (you plot also the last 100 points), the evolution in phase space.
Any help will be apreciated,
Thanks
Gnuplot code for the gif:
set term gif size 1000,600 animate delay 1000 loop 0
set output "animacio.gif"
cd 'C:\Users\Usuario\Desktop'
datafile ="P7-1718-b-res.dat"
do for[i=1:5000:10]{
set multiplot
set size 0.5,0.8
set origin 0.0,0.0
set title "EvoluciĆ³ de l'angle girat i velocitat angular (t)"
set xrange[0:50]
set yrange[-pi:pi]
set xlabel "t (s)"
set ylabel "Angle girat, v_{ang}"
set key below
plot datafile index 9 every ::1::i with line linewidth 4 t"PosiciĆ³ angular" ,datafile index 9 every ::1::i u 1:3 with line linewidth 4 t"V_{ang}"
set origin 0.5,0
set size 0.5,0.8
set title "EvoluciĆ³ en l'espai de fases"
set yrange[-pi:pi]
set xrange[-pi:pi]
set xlabel "Angle girat(rad)"
set ylabel "Velocitat angular(rad/s)"
set key below
if (i>101) {
plot datafile index 9 every::i::i u 2:3 t"" ps 3,datafile index 9 every::i-100::i u 2:3 w l t"" }
else {
plot datafile index 9 every::i::i u 2:3 t"" ps 3}
unset multiplot
}
And assume your data have three rows (time,position,angular velocity) at index 9.

As you mentioned, you can use Matplotlib animation to make it work.
I have done something "similar" to your data, but of course, as I haven't got the data file, it is not equal. The code is the following one:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
w = 1.
t = np.linspace(0,10,200)
x = np.cos(w*t)
v = -w*np.cos(w*t)
fig, ax = plt.subplots(1,2)
line_1, = ax[0].plot([], [], 'b-', lw=2)
line_2, = ax[0].plot([], [], 'r-', lw=2)
ax[0].set_xlim([0,50])
ax[0].set_ylim([-np.pi,np.pi])
line_3, = ax[1].plot([], [], 'g-', lw=2)
star_3, = ax[1].plot([], [], 'g*')
ax[1].set_xlim([-np.pi,np.pi])
ax[1].set_ylim([-np.pi,np.pi])
def animate(i):
line_1.set_data(t[:i],x[:i]) # update the data
line_2.set_data(t[:i],v[:i])
nLast = 20
idFrom = i-nLast if(i-nLast >= 0) else 0
line_3.set_data(np.cos(t[idFrom:i+1]),np.sin(t[idFrom:i+1]))
star_3.set_data(np.cos(t[i]),np.sin(t[i]))
return line_1,line_2,line_3,star_3
# Init only required for blitting to give a clean slate.
def init():
line_1.set_data([], [])
line_2.set_data([], [])
line_3.set_data([], [])
star_3.set_data([], [])
return line_1,line_2,line_3,star_3
anim = animation.FuncAnimation(fig, animate, np.arange(1, len(t)), init_func=init, interval=100, blit=True)
#anim.save('Plot_last_nLast.mp4', fps=15)
#anim.save('Plot_last_nLast.gif', dpi=80, writer='imagemagick')
plt.show()
You can save the animation in a GIF (required Imagemagick) or as a MP4 movie if you have ffmpeg to use it as writer of the animation.
But that's another issue

Related

create boxes on graph in python

I want this kind of result. I want my code to read elements of a text file and if element=='healthy'
it should create a box in a graph and its color should be green ('healthy written in box').
else if element=='unhealthy'
it should create a box and its color should be red (with 'unhealthy written in box').
boxes should be horizontally aligned, and if more than 5 then remaining should start from the next row. (every row should contain only 5 boxes or less).
The end result should display a graph that contains boxes,
red denoting 'unhealthy' and green denoting 'healthy'
I found the following code, but it is not working they way I want it to.
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
from matplotlib import colors
#open text file (percen) that contains healthy/unhealthy
with open('percen.txt', 'r') as f:
result= [int(line) for line in f]
data = np.random.rand(10,10) * 20
cmap = colors.ListedColormap(['green'])
cmap1 = colors.ListedColormap(['red'])
bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots(2,5 , sharex='col', sharey='row')
for i in range(2):
for j in range(5):
for element in result:
if (element=='healthy'):
ax[i,j].text(1, -3, 'healthy',
fontsize=15, ha='center', color='green')
ax[i,j].imshow(data,cmap=cmap, norm=norm)
else:
ax[i,j].text(1, -3, 'unhealthy',
fontsize=15, ha='center', color='red')
ax[i,j].imshow(data,cmap=cmap1,norm=norm)
fig
plt.show()
There are a few different ways you can do this and your code is probably not the best but we can use it as a starting point. Your issue is that you are looping through the plots and then looping through your data again for each plot. Your current code also adds text above the plot. If you want the text above I would recommend adding the label as a title, otherwise when you set your text inside the plot you need to specify the coordinates within the grid.
Below is a modified form of your code, play around with it some more to get what you want.
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
from matplotlib import colors
result = ['healthy', 'unhealthy', 'healthy', 'unhealthy', 'healthy', 'unhealthy', 'healthy', 'healthy', 'unhealthy', 'unhealthy']
data = np.random.rand(10,10) * 20
cmap = colors.ListedColormap(['green'])
cmap1 = colors.ListedColormap(['red'])
bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots(2,5 , sharex='col', sharey='row',figsize=(15,8)) # Added figsize to better show your plot
element_index = 0
for i in range(2):
for j in range(5):
element = result[element_index] #Instead of the for loop, get the corresponding element
if (element=='healthy'):
ax[i,j].text(4.5,4.5, 'healthy',fontsize=15, ha='center' ,color='black',zorder=100) #Change zorder so label is over plot
ax[i,j].imshow(data,cmap=cmap, norm=norm)
ax[i,j].set_yticklabels('') #To remove arbitrary numbers on y axis
ax[i,j].set_xticklabels('') #To remove arbitrary numbers on y axis
elif element == 'unhealthy':
ax[i,j].text(4.5,4.5, 'unhealthy',fontsize=15, ha='center' ,color='black',zorder=100)
ax[i,j].imshow(data,cmap=cmap1,norm=norm)
ax[i,j].set_yticklabels('') #To remove arbitrary numbers on y axis
ax[i,j].set_xticklabels('') #To remove arbitrary numbers on x axis
element_index+=1 #Add 1 to the index so we get the next value for the next plot
fig
plt.show()

python animation reading data from file

I'm trying to plot the time evolution of a function f(x,t). The data is stored in a file which has the following format:
1st row:f(0,0) f(0,1) f(0,2) ....f(0,N)
2nd row:f(1,0) f(1,1) f(1,2) ....f(1,N)
Mth row:f(M,0) f(M,1) f(M,2) ....f(M,N)
where N is the no: of points of the simulation box and M is the number of timesteps.
I used basic_animation by Jake Vanderplas (https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/) to start with, the original example works fine as long as i put blit=False.
Then i tried to replace x by :
x= np.arange(0,192)
and y by the contents of the file mentioned above.
If i do just plt.plot(x,y), it does plot f(x,t) at a given time t, but I want the animation of f(x,t) in time.
set_data should accept 2 1Darrays and I've checked that len(x)=len(y).
But I get the following error message:
'RuntimeError: xdata and ydata must be the same length'
This is the code (in the future i would like to plot multiple functions):
"""
Modified Matplotlib Animation Example
original example:
email: vanderplas#astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Feel free to use and modify this, but keep the above information.
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from itertools import islice
filename = 'DensityByPropagation__a_0_VHxcS_kick'
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 192), ylim=(-2, 2))
lineS, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
lineS.set_data([], [])
return lineS,
# animation function. This is called sequentially
def animate(i):
w = np.linspace(0, 2, 1000)
z = np.sin(2 * np.pi * (w - 0.01 * i))
x= np.arange(0,192)
with open(filename) as fobj:
ketchup = islice(fobj, 0, None, 10)
for line in ketchup:
x,y = x,zip(*([float(y) for y in line.split("\t")] for line in fobj))
#plt.plot(x,y)
#plt.show()
#print len(x)
#print len(y)
#lineS.set_data(w,z)
lineS.set_data(x,y)
return lineS,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=False)
# save the animation as an mp4. This requires ffmpeg or mencoder to be
# installed. The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5. You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('movieJoh.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
I'm not sure what exactly is causing your error, but let me point something out, then I'll make a toy example that should help clarify what's happening.
These lines seem unnecessarily complicated.
with open(filename) as fobj:
ketchup = islice(fobj, 0, None, 10)
for line in ketchup:
x,y = x,zip(*([float(y) for y in line.split("\t")] for line in fobj))
If your data is in fact in the simple format you stated, i.e., values separated by spaces, np.loadtxt() would load all the values into an easy to manage array.
Example
Lets assume this is your data file (10 time steps, 2 points on plot at each step):
0 0 0 0 0 0 0 0 0 0
9 8 7 6 5 4 3 2 1 0
Now some code:
filename = 'data.txt'
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 1), ylim=(0, 9))
lineS, = ax.plot([], [], lw=2)
x = range(2) # the domain
Now we load the data in with np.loadtxt(), this creates a 2-d matrix with t in the columns and x in the rows. We then transpose it to make indexing each time step possible in animate().
# load the data from file
data = np.loadtxt(filename)
# transpose so we could easily index in the animate() function
data = np.transpose(data)
Now for animation functions. This part is really quite simple. animate(i) takes one argument - the frame number. Using the frame number, we extract the values of f(x,t=frameNumber) and set that as the data on the plot.
# initialization function: plot the background of each frame
def init():
lineS.set_data([], [])
return lineS,
# animation function. This is called sequentially
def animate(i):
lineS.set_data(x, data[i])
return lineS,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=10, interval=100, blit=True)
plt.show()
This is the working code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Input
filename = 'PeriodicDensity' # Filename
x = np.linspace(-7.5,7.5,192) # Domain
xLimits=[-7.5,7.5] # x limits
yLimits=[0,1] # y limits
framesToUse = range(1,9000,150)# The time-steps to plot
# load the data from file
data = np.loadtxt(filename)
# Set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=xLimits,ylim=yLimits)
lineS, = ax.plot([], [], lw=2)
# Initialisation function
def init():
lineS.set_data([],[])
return lineS,
# Animation function (called sequentially)
def animate(i):
lineS.set_data(x,data[i])
return lineS,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,interval=1000, frames=framesToUse, blit=True)
# save the animation as an mp4. This requires ffmpeg or mencoder to be
# installed. The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5. You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('movieDensity.mp4', fps=1, extra_args=['-vcodec', 'libx264'])
plt.show()

How to move figure window in interactive mode in matplotlib?

I'm trying to monitor real-time data with matplotlib.
I found that I can update plot dynamically with interactive mode in Pyplot.
And it worked well, but one problem is 'I cannot manipulate the figure window at all'. For example, move or re-size the figure window.
Here is my code.
This is cons of interactive mode? or I'm using it incorrectly?
import matplotlib.pyplot as plt
import time
import math
# generate data
x = [0.1*_a for _a in range(1000)]
y = map(lambda x : math.sin(x), x)
# interactive mode
plt.ion() # identical plt.interactive(True)
fig, ax = plt.subplots()
# ax = plt.gca()
lines, = ax.plot([], [])
# ax.set_ylim(-1, 1)
ax.grid()
MAX_N_DATA = 100
x_data = []
y_data = []
for i in range(len(x)):
# New data received
x_data.append(x[i])
y_data.append(y[i])
# limit data length
if x_data.__len__() > MAX_N_DATA:
x_data.pop(0)
y_data.pop(0)
# Set Data
lines.set_xdata(x_data)
lines.set_ydata(y_data)
# The data limits are not updated automatically.
ax.relim()
# with tight True, graph flows smoothly.
ax.autoscale_view(tight=True, scalex=True, scaley=True)
# draw
plt.draw()
time.sleep(0.01)
Thank you.
As shown in this answer to another question, replace plt.draw() with plt.pause(0.05). This solved the problem for me.
Although I still think you should use bokeh, I'll tell you how to do it with matplotlib.
The problem why it won't work ist that matplotlib's event loop is not active and therefore it cannot digest window events (like close or resize). Unfortunately it is not possible to trigger this digestion from the outside. What you have to do is to use matplotlib's animation system.
Your code is actually quite well prepared for it so you can use FuncAnimation.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import math
# generate data
x = [0.1*_a for _a in range(1000)]
y = map(lambda x : math.sin(x), x)
# don't need ion, we're using block=True (see end of code)
fig, ax = plt.subplots()
fig.show()
# ax = plt.gca()
lines, = ax.plot([], [])
# ax.set_ylim(-1, 1)
ax.grid()
MAX_N_DATA = 100
x_data = []
y_data = []
def showdata(i):
# New data received
x_data.append(x[i])
y_data.append(y[i])
# limit data length
if x_data.__len__() > MAX_N_DATA:
x_data.pop(0)
y_data.pop(0)
# Set Data
lines.set_xdata(x_data)
lines.set_ydata(y_data)
# The data limits are not updated automatically.
ax.relim()
# with tight True, graph flows smoothly.
ax.autoscale_view(tight=True, scalex=True, scaley=True)
# draw will be called by the animation system
# instead of time.sleep(0.01) we use an update interval of 10ms
# which has the same effect
anim = FuncAnimation(fig, showdata, range(len(x)), interval=10, repeat=False)
# start eventloop
plt.show(block=True)

Matplotlib update a graph with new data, graph does not show

I have much the same problem as this guy: Dynamically updating plot in matplotlib. I want to update a graph with data from a serial port and I have been trying to implement this answer, but I can't get a MWE to work. The graph simply doesn't appear, but everything else seems to work. I have read about problems with the installation of Matplotlib causing similar symptoms.
Here is my Minimum Not Working Example (MNWE):
import numpy as np
import matplotlib.pyplot as plt
fig1 = plt.figure() #Create figure
l, = plt.plot([], [], 'r-') #What is the comma for? Is l some kind of struct/class?
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
k = 5
xdata=[0.5 for i in range(k+1)] # Generate a list to hold data
ydata=[j for j in range(k+1)]
while True:
y = float(raw_input("y val :"))
xdata.append(y) # Append new data to list
k = k + 1 # inc x value
ydata.append(k)
l.set_data(xdata,ydata) # update data
print xdata # Print for debug perposes
print ydata
plt.draw # These seem to do nothing
plt.show # !?
Could someone please point me in the right direction / provide a link / tell me what to google? I'm lost. Thanks
As suggested by user #fhdrsdg I was missing brackets. Getting the rescale to work requires code from: set_data and autoscale_view matplotlib
A working MWE is provided below:
import numpy as np
import matplotlib.pyplot as plt
plt.ion() # Enable interactive mode
fig = plt.figure() # Create figure
axes = fig.add_subplot(111) # Add subplot (dont worry only one plot appears)
axes.set_autoscale_on(True) # enable autoscale
axes.autoscale_view(True,True,True)
l, = plt.plot([], [], 'r-') # Plot blank data
plt.xlabel('x') # Set up axes
plt.title('test')
k = 5
xdata=[0.5 for i in range(k+1)] # Generate a list to hold data
ydata=[j for j in range(k+1)]
while True:
y = float(raw_input("y val :")) #Get new data
xdata.append(y) # Append new data to list
k = k + 1 # inc x value
ydata.append(k)
l.set_data(ydata,xdata) # update data
print xdata # Print for debug perposes
print ydata
axes.relim() # Recalculate limits
axes.autoscale_view(True,True,True) #Autoscale
plt.draw() # Redraw

3D animation with matplotlib, connect points to create moving stick figure

I am currently having some trouble with my code which animates some time-series data, and I cannot quite figure it out. Basically I have 12 tags which I am animating through time. Each tag has a trajectory in time such that the movement path can be seen for each tag as it progresses (have a look at the image attached). Now I would like the animation to also include the lines between pairs of tags (i.e. pairs of points - for example, how to add an animation line between the yellow and green tags), but I am not entirely sure how to do this. This is code adapted from jakevdp.github.io.
Here is the code thus far.
"""
Full animation of a walking event (note: a lot of missing data)
"""
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg') # Need to use in order to run on mac
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
#=============================================================================================
t_start = 1917 # start frame
t_end = 2130 # end frame
data = pd.read_csv('~/Smart-first_phase_NaN-zeros.csv') # only coordinate data
df = data.loc[t_start:t_end,'Shoulder_left_x':'Ankle_right_z']
# Find max and min values for animation ranges
df_minmax = pd.DataFrame(index=list('xyz'),columns=range(2))
for i in list('xyz'):
c_max = df.filter(regex='_{}'.format(i)).max().max()
c_min = df.filter(regex='_{}'.format(i)).min().min()
df_minmax.ix[i] = np.array([c_min,c_max])
df_minmax = 1.3*df_minmax # increase by 30% to make animation look better
df.columns = np.repeat(range(12),3) # store cols like this for simplicity
N_tag = df.shape[1]/3 # nr of tags used (all)
N_trajectories = N_tag
t = np.linspace(0,data.Time[t_end],df.shape[0]) # pseudo time-vector for first walking activity
x_t = np.zeros(shape=(N_tag,df.shape[0],3)) # empty animation array (3D)
for tag in range(12):
# store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
x_t[tag,:,:] = df[tag]
#===STICK-LINES========================================================================================
#xx = [x_t[1,:,0],x_t[2,:,0]]
#yy = [x_t[1,:,1],x_t[2,:,1]]
#zz = [x_t[1,:,2],x_t[2,:,2]]
#======================================================================================================
# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
# set up lines which create the stick figures
stick_lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# prepare the axes limits
ax.set_xlim(df_minmax.ix['x'].values)
ax.set_ylim(df_minmax.ix['z'].values) # note usage of z coordinate
ax.set_zlim(df_minmax.ix['y'].values) # note usage of y coordinate
# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)
# initialization function: plot the background of each frame
def init():
for line, pt, stick_line in zip(lines, pts, stick_lines):
# trajectory lines
line.set_data([], [])
line.set_3d_properties([])
# points
pt.set_data([], [])
pt.set_3d_properties([])
# stick lines
stick_line.set_data([], [])
stick_line.set_3d_properties([])
return lines + pts + stick_lines
# animation function. This will be called sequentially with the frame number
def animate(i):
# we'll step two time-steps per frame. This leads to nice results.
i = (5 * i) % x_t.shape[1]
for line, pt, stick_line, xi in zip(lines, pts, stick_lines, x_t):
x, z, y = xi[:i].T # note ordering of points to line up with true exogenous registration (x,z,y)
# trajectory lines
line.set_data(x,y)
line.set_3d_properties(z)
# points
pt.set_data(x[-1:], y[-1:])
pt.set_3d_properties(z[-1:])
# stick lines
#stick_line.set_data(xx,zz)
#stick_line.set_3d_properties(yy)
ax.view_init(30, 0.3 * i)
fig.canvas.draw()
return lines + pts + stick_lines
# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=30, blit=True)
# Save as mp4. This requires mplayer or ffmpeg to be installed
#anim.save('lorentz_attractor.mp4', fps=15, extra_args=['-vcodec', 'libx264'])
plt.show()
So, to conclude: I would like lines that moves with the point pairs (orange, yellow) and (yellow, green). If someone could show me how to do that I should be able to extrapolate the methods to the rest of the animation.
As ever, any help is much appreciated.
The original data can be found here, if anyone wants to replicate: https://www.dropbox.com/sh/80f8ue4ffa4067t/Pntl5-gUW4
EDIT: IMPLEMENTED SOLUTION
Here is the final result, using the proposed solution.
I modified your code to add stick lines, but to simplify the code, I removed the trace lines:
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg') # Need to use in order to run on mac
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
#=============================================================================================
t_start = 1917 # start frame
t_end = 2130 # end frame
data = pd.read_csv('Smart-first_phase_NaN-zeros.csv') # only coordinate data
df = data.loc[t_start:t_end,'Shoulder_left_x':'Ankle_right_z']
# Find max and min values for animation ranges
df_minmax = pd.DataFrame(index=list('xyz'),columns=range(2))
for i in list('xyz'):
c_max = df.filter(regex='_{}'.format(i)).max().max()
c_min = df.filter(regex='_{}'.format(i)).min().min()
df_minmax.ix[i] = np.array([c_min,c_max])
df_minmax = 1.3*df_minmax # increase by 30% to make animation look better
df.columns = np.repeat(range(12),3) # store cols like this for simplicity
N_tag = df.shape[1]/3 # nr of tags used (all)
N_trajectories = N_tag
t = np.linspace(0,data.Time[t_end],df.shape[0]) # pseudo time-vector for first walking activity
x_t = np.zeros(shape=(N_tag,df.shape[0],3)) # empty animation array (3D)
for tag in range(12):
# store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
x_t[tag,:,:] = df[tag]
x_t = x_t[:, :, [0, 2, 1]]
# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
# set up lines which create the stick figures
stick_defines = [
(0, 1),
(1, 2),
(3, 4),
(4, 5),
(6, 7),
(7, 8),
(9, 10),
(10, 11)
]
stick_lines = [ax.plot([], [], [], 'k-')[0] for _ in stick_defines]
# prepare the axes limits
ax.set_xlim(df_minmax.ix['x'].values)
ax.set_ylim(df_minmax.ix['z'].values) # note usage of z coordinate
ax.set_zlim(df_minmax.ix['y'].values) # note usage of y coordinate
# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)
# initialization function: plot the background of each frame
def init():
for line, pt in zip(lines, pts):
# trajectory lines
line.set_data([], [])
line.set_3d_properties([])
# points
pt.set_data([], [])
pt.set_3d_properties([])
return lines + pts + stick_lines
# animation function. This will be called sequentially with the frame number
def animate(i):
# we'll step two time-steps per frame. This leads to nice results.
i = (5 * i) % x_t.shape[1]
for line, pt, xi in zip(lines, pts, x_t):
x, y, z = xi[:i].T # note ordering of points to line up with true exogenous registration (x,z,y)
pt.set_data(x[-1:], y[-1:])
pt.set_3d_properties(z[-1:])
for stick_line, (sp, ep) in zip(stick_lines, stick_defines):
stick_line._verts3d = x_t[[sp,ep], i, :].T.tolist()
ax.view_init(30, 0.3 * i)
fig.canvas.draw()
return lines + pts + stick_lines
# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=30, blit=True)
plt.show()
Here is one frame of the animation:

Categories