PK rIP
F 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\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 numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef data_gen(t=0):\n cnt = 0\n while cnt < 1000:\n cnt += 1\n t += 0.1\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, blit=False, interval=10,\n repeat=False, 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.8.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK rIPv " 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\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 = np.array(bins[:-1])\nright = np.array(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 ``plt.Path.MOVETO``, ``plt.Path.LINETO`` and\n``plt.Path.CLOSEPOLY`` for each rect.\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.ones(nverts, int) * 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` instance, and setup\nthe `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, 100, 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.8.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK rIPQ 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\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.8.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK rIPz; ; 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\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(object):\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, 15)\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 init(self):\n self.success = 0\n self.line.set_data([], [])\n return self.line,\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 return self.init()\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=np.arange(100), init_func=ud.init,\n 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.8.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK rIP &