PK %s"RV! " animation/animated_histogram.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated histogram\n\nUse a path patch to draw a bunch of rectangles for an animated histogram.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.path as path\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n# histogram our data with numpy\ndata = np.random.randn(1000)\nn, bins = np.histogram(data, 100)\n\n# get the corners of the rectangles for the histogram\nleft = bins[:-1]\nright = bins[1:]\nbottom = np.zeros(len(left))\ntop = bottom + n\nnrects = len(left)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here comes the tricky part -- we have to set up the vertex and path codes\narrays using `.Path.MOVETO`, `.Path.LINETO` and `.Path.CLOSEPOLY` for each\nrect.\n\n* We need 1 ``MOVETO`` per rectangle, which sets the initial point.\n* We need 3 ``LINETO``'s, which tell Matplotlib to draw lines from\n vertex 1 to vertex 2, v2 to v3, and v3 to v4.\n* We then need one ``CLOSEPOLY`` which tells Matplotlib to draw a line from\n the v4 to our initial vertex (the ``MOVETO`` vertex), in order to close the\n polygon.\n\n
Note
The vertex for ``CLOSEPOLY`` is ignored, but we still need a placeholder\n in the ``verts`` array to keep the codes aligned with the vertices.
\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"nverts = nrects * (1 + 3 + 1)\nverts = np.zeros((nverts, 2))\ncodes = np.full(nverts, path.Path.LINETO)\ncodes[0::5] = path.Path.MOVETO\ncodes[4::5] = path.Path.CLOSEPOLY\nverts[0::5, 0] = left\nverts[0::5, 1] = bottom\nverts[1::5, 0] = left\nverts[1::5, 1] = top\nverts[2::5, 0] = right\nverts[2::5, 1] = top\nverts[3::5, 0] = right\nverts[3::5, 1] = bottom"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To animate the histogram, we need an ``animate`` function, which generates\na random set of numbers and updates the locations of the vertices for the\nhistogram (in this case, only the heights of each rectangle). ``patch`` will\neventually be a `.Patch` object.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"patch = None\n\n\ndef animate(i):\n # simulate new data coming in\n data = np.random.randn(1000)\n n, bins = np.histogram(data, 100)\n top = bottom + n\n verts[1::5, 1] = top\n verts[2::5, 1] = top\n return [patch, ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And now we build the `.Path` and `.Patch` instances for the histogram using\nour vertices and codes. We add the patch to the `~.axes.Axes` instance, and\nsetup the `.FuncAnimation` with our ``animate`` function.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\nbarpath = path.Path(verts, codes)\npatch = patches.PathPatch(\n barpath, facecolor='green', edgecolor='yellow', alpha=0.5)\nax.add_patch(patch)\n\nax.set_xlim(left[0], right[-1])\nax.set_ylim(bottom.min(), top.max())\n\nani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK @s"ROm animation/dynamic_image.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated image using a precomputed list of images\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig, ax = plt.subplots()\n\n\ndef f(x, y):\n return np.sin(x) + np.cos(y)\n\nx = np.linspace(0, 2 * np.pi, 120)\ny = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)\n\n# ims is a list of lists, each row is a list of artists to draw in the\n# current frame; here we are just animating one artist, the image, in\n# each frame\nims = []\nfor i in range(60):\n x += np.pi / 15.\n y += np.pi / 20.\n im = ax.imshow(f(x, y), animated=True)\n if i == 0:\n ax.imshow(f(x, y)) # show an initial one first\n ims.append([im])\n\nani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,\n repeat_delay=1000)\n\n# To save the animation, use e.g.\n#\n# ani.save(\"movie.mp4\")\n#\n# or\n#\n# writer = animation.FFMpegWriter(\n# fps=15, metadata=dict(artist='Me'), bitrate=1800)\n# ani.save(\"movie.mp4\", writer=writer)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK Js"R
{M M animation/random_walk.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated 3D random walk\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef gen_rand_line(length, dims=2):\n \"\"\"\n Create a line using a random walk algorithm.\n\n Parameters\n ----------\n length : int\n The number of points of the line.\n dims : int\n The number of dimensions of the line.\n \"\"\"\n line_data = np.empty((dims, length))\n line_data[:, 0] = np.random.rand(dims)\n for index in range(1, length):\n # scaling the random numbers by 0.1 so\n # movement is small compared to position.\n # subtraction by 0.5 is to change the range to [-0.5, 0.5]\n # to allow a line to move backwards.\n step = (np.random.rand(dims) - 0.5) * 0.1\n line_data[:, index] = line_data[:, index - 1] + step\n return line_data\n\n\ndef update_lines(num, data_lines, lines):\n for line, data in zip(lines, data_lines):\n # NOTE: there is no .set_data() for 3 dim data...\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n return lines\n\n\n# Attaching 3D axis to the figure\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\n\n# Fifty lines of random 3-D lines\ndata = [gen_rand_line(25, 3) for index in range(50)]\n\n# Creating fifty line objects.\n# NOTE: Can't pass empty arrays into 3d version of plot()\nlines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]\n\n# Setting the axes properties\nax.set_xlim3d([0.0, 1.0])\nax.set_xlabel('X')\n\nax.set_ylim3d([0.0, 1.0])\nax.set_ylabel('Y')\n\nax.set_zlim3d([0.0, 1.0])\nax.set_zlabel('Z')\n\nax.set_title('3D Test')\n\n# Creating the Animation object\nline_ani = animation.FuncAnimation(\n fig, update_lines, 50, fargs=(data, lines), interval=50)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK Ns"RqR R animation/simple_anim.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Animated line plot\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig, ax = plt.subplots()\n\nx = np.arange(0, 2*np.pi, 0.01)\nline, = ax.plot(x, np.sin(x))\n\n\ndef animate(i):\n line.set_ydata(np.sin(x + i / 50)) # update the data.\n return line,\n\n\nani = animation.FuncAnimation(\n fig, animate, interval=20, blit=True, save_count=50)\n\n# To save the animation, use e.g.\n#\n# ani.save(\"movie.mp4\")\n#\n# or\n#\n# writer = animation.FFMpegWriter(\n# fps=15, metadata=dict(artist='Me'), bitrate=1800)\n# ani.save(\"movie.mp4\", writer=writer)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK \s"R+ animation/unchained.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# MATPLOTLIB **UNCHAINED**\n\nComparative path demonstration of frequency from a fake signal of a pulsar\n(mostly known because of the cover for Joy Division's Unknown Pleasures).\n\nAuthor: Nicolas P. Rougier\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# Create new Figure with black background\nfig = plt.figure(figsize=(8, 8), facecolor='black')\n\n# Add a subplot with no frame\nax = plt.subplot(111, frameon=False)\n\n# Generate random data\ndata = np.random.uniform(0, 1, (64, 75))\nX = np.linspace(-1, 1, data.shape[-1])\nG = 1.5 * np.exp(-4 * X ** 2)\n\n# Generate line plots\nlines = []\nfor i in range(len(data)):\n # Small reduction of the X extents to get a cheap perspective effect\n xscale = 1 - i / 200.\n # Same for linewidth (thicker strokes on bottom)\n lw = 1.5 - i / 100.0\n line, = ax.plot(xscale * X, i + G * data[i], color=\"w\", lw=lw)\n lines.append(line)\n\n# Set y limit (or first line is cropped because of thickness)\nax.set_ylim(-1, 70)\n\n# No ticks\nax.set_xticks([])\nax.set_yticks([])\n\n# 2 part titles to get different font weights\nax.text(0.5, 1.0, \"MATPLOTLIB \", transform=ax.transAxes,\n ha=\"right\", va=\"bottom\", color=\"w\",\n family=\"sans-serif\", fontweight=\"light\", fontsize=16)\nax.text(0.5, 1.0, \"UNCHAINED\", transform=ax.transAxes,\n ha=\"left\", va=\"bottom\", color=\"w\",\n family=\"sans-serif\", fontweight=\"bold\", fontsize=16)\n\n\ndef update(*args):\n # Shift all data to the right\n data[:, 1:] = data[:, :-1]\n\n # Fill-in new values\n data[:, 0] = np.random.uniform(0, 1, len(data))\n\n # Update data\n for i in range(len(data)):\n lines[i].set_ydata(i + G * data[i])\n\n # Return modified artists\n return lines\n\n# Construct the animation, using the update function as the animation director.\nanim = animation.FuncAnimation(fig, update, interval=10)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK /s"RZ{!
animation/bayes_update.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The Bayes update\n\nThis animation displays the posterior estimate updates as it is refitted when\nnew data arrives.\nThe vertical line represents the theoretical value to which the plotted\ndistribution should converge.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import math\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\ndef beta_pdf(x, a, b):\n return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)\n / (math.gamma(a) * math.gamma(b)))\n\n\nclass UpdateDist:\n def __init__(self, ax, prob=0.5):\n self.success = 0\n self.prob = prob\n self.line, = ax.plot([], [], 'k-')\n self.x = np.linspace(0, 1, 200)\n self.ax = ax\n\n # Set up plot parameters\n self.ax.set_xlim(0, 1)\n self.ax.set_ylim(0, 10)\n self.ax.grid(True)\n\n # This vertical line represents the theoretical value, to\n # which the plotted distribution should converge.\n self.ax.axvline(prob, linestyle='--', color='black')\n\n def __call__(self, i):\n # This way the plot can continuously run and we just keep\n # watching new realizations of the process\n if i == 0:\n self.success = 0\n self.line.set_data([], [])\n return self.line,\n\n # Choose success based on exceed a threshold with a uniform pick\n if np.random.rand(1,) < self.prob:\n self.success += 1\n y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)\n self.line.set_data(self.x, y)\n return self.line,\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nfig, ax = plt.subplots()\nud = UpdateDist(ax, prob=0.7)\nanim = FuncAnimation(fig, ud, frames=100, interval=100, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK 8s"Rb
animation/double_pendulum.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# The double pendulum problem\n\nThis animation illustrates the double pendulum problem.\n\nDouble pendulum formula translated from the C code at\nhttp://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from numpy import sin, cos\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\nimport matplotlib.animation as animation\n\nG = 9.8 # acceleration due to gravity, in m/s^2\nL1 = 1.0 # length of pendulum 1 in m\nL2 = 1.0 # length of pendulum 2 in m\nM1 = 1.0 # mass of pendulum 1 in kg\nM2 = 1.0 # mass of pendulum 2 in kg\nt_stop = 5 # how many seconds to simulate\n\n\ndef derivs(state, t):\n\n dydx = np.zeros_like(state)\n dydx[0] = state[1]\n\n delta = state[2] - state[0]\n den1 = (M1+M2) * L1 - M2 * L1 * cos(delta) * cos(delta)\n dydx[1] = ((M2 * L1 * state[1] * state[1] * sin(delta) * cos(delta)\n + M2 * G * sin(state[2]) * cos(delta)\n + M2 * L2 * state[3] * state[3] * sin(delta)\n - (M1+M2) * G * sin(state[0]))\n / den1)\n\n dydx[2] = state[3]\n\n den2 = (L2/L1) * den1\n dydx[3] = ((- M2 * L2 * state[3] * state[3] * sin(delta) * cos(delta)\n + (M1+M2) * G * sin(state[0]) * cos(delta)\n - (M1+M2) * L1 * state[1] * state[1] * sin(delta)\n - (M1+M2) * G * sin(state[2]))\n / den2)\n\n return dydx\n\n# create a time array from 0..100 sampled at 0.05 second steps\ndt = 0.05\nt = np.arange(0, t_stop, dt)\n\n# th1 and th2 are the initial angles (degrees)\n# w10 and w20 are the initial angular velocities (degrees per second)\nth1 = 120.0\nw1 = 0.0\nth2 = -10.0\nw2 = 0.0\n\n# initial state\nstate = np.radians([th1, w1, th2, w2])\n\n# integrate your ODE using scipy.integrate.\ny = integrate.odeint(derivs, state, t)\n\nx1 = L1*sin(y[:, 0])\ny1 = -L1*cos(y[:, 0])\n\nx2 = L2*sin(y[:, 2]) + x1\ny2 = -L2*cos(y[:, 2]) + y1\n\nfig = plt.figure(figsize=(5, 4))\nax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 1))\nax.set_aspect('equal')\nax.grid()\n\nline, = ax.plot([], [], 'o-', lw=2)\ntime_template = 'time = %.1fs'\ntime_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)\n\n\ndef animate(i):\n thisx = [0, x1[i], x2[i]]\n thisy = [0, y1[i], y2[i]]\n\n line.set_data(thisx, thisy)\n time_text.set_text(time_template % (i*dt))\n return line, time_text\n\n\nani = animation.FuncAnimation(\n fig, animate, len(y), interval=dt*1000, blit=True)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK Vs"R)
animation/strip_chart.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Oscilloscope\n\nEmulates an oscilloscope.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nfrom matplotlib.lines import Line2D\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\nclass Scope:\n def __init__(self, ax, maxt=2, dt=0.02):\n self.ax = ax\n self.dt = dt\n self.maxt = maxt\n self.tdata = [0]\n self.ydata = [0]\n self.line = Line2D(self.tdata, self.ydata)\n self.ax.add_line(self.line)\n self.ax.set_ylim(-.1, 1.1)\n self.ax.set_xlim(0, self.maxt)\n\n def update(self, y):\n lastt = self.tdata[-1]\n if lastt > self.tdata[0] + self.maxt: # reset the arrays\n self.tdata = [self.tdata[-1]]\n self.ydata = [self.ydata[-1]]\n self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)\n self.ax.figure.canvas.draw()\n\n t = self.tdata[-1] + self.dt\n self.tdata.append(t)\n self.ydata.append(y)\n self.line.set_data(self.tdata, self.ydata)\n return self.line,\n\n\ndef emitter(p=0.1):\n \"\"\"Return a random value in [0, 1) with probability p, else 0.\"\"\"\n while True:\n v = np.random.rand(1)\n if v > p:\n yield 0.\n else:\n yield np.random.rand(1)\n\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801 // 10)\n\n\nfig, ax = plt.subplots()\nscope = Scope(ax)\n\n# pass a generator in \"emitter\" to produce data for the update func\nani = animation.FuncAnimation(fig, scope.update, emitter, interval=50,\n blit=True)\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK As"RҺ % animation/frame_grabbing_sgskip.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Frame grabbing\n\nUse a MovieWriter directly to grab individual frames and write them to a\nfile. This avoids any event loop integration, and thus works even with the Agg\nbackend. This is not recommended for use in an interactive setting.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FFMpegWriter\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\nmetadata = dict(title='Movie Test', artist='Matplotlib',\n comment='Movie support!')\nwriter = FFMpegWriter(fps=15, metadata=metadata)\n\nfig = plt.figure()\nl, = plt.plot([], [], 'k-o')\n\nplt.xlim(-5, 5)\nplt.ylim(-5, 5)\n\nx0, y0 = 0, 0\n\nwith writer.saving(fig, \"writer_test.mp4\", 100):\n for i in range(100):\n x0 += 0.1 * np.random.randn()\n y0 += 0.1 * np.random.randn()\n l.set_data(x0, y0)\n writer.grab_frame()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK Ds"Rooa
a
animation/rain.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Rain simulation\n\nSimulates rain drops on a surface by animating the scale and opacity\nof 50 scatter points.\n\nAuthor: Nicolas P. Rougier\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# Create new Figure and an Axes which fills it.\nfig = plt.figure(figsize=(7, 7))\nax = fig.add_axes([0, 0, 1, 1], frameon=False)\nax.set_xlim(0, 1), ax.set_xticks([])\nax.set_ylim(0, 1), ax.set_yticks([])\n\n# Create rain data\nn_drops = 50\nrain_drops = np.zeros(n_drops, dtype=[('position', float, 2),\n ('size', float, 1),\n ('growth', float, 1),\n ('color', float, 4)])\n\n# Initialize the raindrops in random positions and with\n# random growth rates.\nrain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))\nrain_drops['growth'] = np.random.uniform(50, 200, n_drops)\n\n# Construct the scatter which we will update during animation\n# as the raindrops develop.\nscat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],\n s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],\n facecolors='none')\n\n\ndef update(frame_number):\n # Get an index which we can use to re-spawn the oldest raindrop.\n current_index = frame_number % n_drops\n\n # Make all colors more transparent as time progresses.\n rain_drops['color'][:, 3] -= 1.0/len(rain_drops)\n rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)\n\n # Make all circles bigger.\n rain_drops['size'] += rain_drops['growth']\n\n # Pick a new position for oldest rain drop, resetting its size,\n # color and growth factor.\n rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)\n rain_drops['size'][current_index] = 5\n rain_drops['color'][current_index] = (0, 0, 0, 1)\n rain_drops['growth'][current_index] = np.random.uniform(50, 200)\n\n # Update the scatter collection, with the new colors, sizes and positions.\n scat.set_edgecolors(rain_drops['color'])\n scat.set_sizes(rain_drops['size'])\n scat.set_offsets(rain_drops['position'])\n\n\n# Construct the animation, using the update function as the animation director.\nanimation = FuncAnimation(fig, update, interval=10)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK *s"R animation/animation_demo.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# pyplot animation\n\nGenerating an animation by calling `~.pyplot.pause` between plotting commands.\n\nThe method shown here is only suitable for simple, low-performance use. For\nmore demanding applications, look at the :mod:`.animation` module and the\nexamples that use it.\n\nNote that calling `time.sleep` instead of `~.pyplot.pause` would *not* work.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(19680801)\ndata = np.random.random((50, 50, 50))\n\nfig, ax = plt.subplots()\n\nfor i in range(len(data)):\n ax.cla()\n ax.imshow(data[i])\n ax.set_title(\"frame {}\".format(i))\n # Note that using time.sleep does *not* work here!\n plt.pause(0.1)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK !s"Rz% animation/animate_decay.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Decay\n\nThis example showcases:\n- using a generator to drive an animation,\n- changing axes limits during an animation.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import itertools\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef data_gen():\n for cnt in itertools.count():\n t = cnt / 10\n yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)\n\n\ndef init():\n ax.set_ylim(-1.1, 1.1)\n ax.set_xlim(0, 10)\n del xdata[:]\n del ydata[:]\n line.set_data(xdata, ydata)\n return line,\n\nfig, ax = plt.subplots()\nline, = ax.plot([], [], lw=2)\nax.grid()\nxdata, ydata = [], []\n\n\ndef run(data):\n # update the data\n t, y = data\n xdata.append(t)\n ydata.append(y)\n xmin, xmax = ax.get_xlim()\n\n if t >= xmax:\n ax.set_xlim(xmin, 2*xmax)\n ax.figure.canvas.draw()\n line.set_data(xdata, ydata)\n\n return line,\n\nani = animation.FuncAnimation(fig, run, data_gen, interval=10, init_func=init)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK s"R } &