Created
September 3, 2012 20:23
-
-
Save anonymous/3613113 to your computer and use it in GitHub Desktop.
matplotlib animation code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib.lines import Line2D | |
import matplotlib.animation as animation | |
from matplotlib import gridspec | |
class PlotSpec(object): | |
def __init__(self, xdata, ydata, xlabel, ylabel, subgrid_specs): | |
self.xdata = xdata | |
self.ydata = ydata | |
self.line = Line2D([], [], color='black') | |
self.axes = plt.subplot2grid(*subgrid_specs) | |
self.axes.add_line(self.line) | |
self.axes.set_xlabel(xlabel) | |
self.axes.set_xlabel(ylabel) | |
class DataAnimator(object): | |
def __init__(self): | |
self.fig = plt.figure() | |
# data 1 | |
x = np.linspace(0,10,100) | |
d1 = PlotSpec(x, np.sin(x), 'x1', 'y1', ((1,2), (0,0))) | |
# data 2 | |
d2 = PlotSpec(x, np.cos(x), 'x2', 'y2', ((1,2), (0,1))) | |
self.all_plotspecs = [d1,d2] | |
ani = animation.FuncAnimation(self.fig, self._update_frame, init_func=self._setup) | |
def _setup(self): | |
pltobjects = [] | |
for spec in self.all_plotspecs: | |
spec.line.set_data([], []) | |
pltobjects.append(spec.line) | |
return pltobjects | |
def show(self): | |
plt.show() | |
def _update_frame(self, fnum): | |
pltobjects = [] | |
for spec in self.all_plotspecs: | |
xdata, ydata = spec.xdata, spec.ydata | |
offset = 3 | |
f = fnum + 1 | |
head_slice = (xdata > xdata[f] - offset) & (xdata < xdata[f]) | |
spec.line.set_data(xdata[:f], ydata[:f]) | |
pltobjects.append(spec.line) | |
return pltobjects | |
#----------------------------------------------------------------------------- | |
if __name__ == '__main__': | |
da = DataAnimator() | |
da.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment