Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 28 additions & 64 deletions examples/animation/animated_histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,89 +3,53 @@
Animated histogram
==================

Use a path patch to draw a bunch of rectangles for an animated histogram.
Use histogram's `.BarContainer` to draw a bunch of rectangles for an animated
histogram.
"""

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation

# Fixing random state for reproducibility
np.random.seed(19680801)
# Fixing bin edges
HIST_BINS = np.linspace(-4, 4, 100)

# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)

# get the corners of the rectangles for the histogram
left = bins[:-1]
right = bins[1:]
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)

###############################################################################
# Here comes the tricky part -- we have to set up the vertex and path codes
# arrays using `.Path.MOVETO`, `.Path.LINETO` and `.Path.CLOSEPOLY` for each
# rect.
#
# * We need 1 ``MOVETO`` per rectangle, which sets the initial point.
# * We need 3 ``LINETO``'s, which tell Matplotlib to draw lines from
# vertex 1 to vertex 2, v2 to v3, and v3 to v4.
# * We then need one ``CLOSEPOLY`` which tells Matplotlib to draw a line from
# the v4 to our initial vertex (the ``MOVETO`` vertex), in order to close the
# polygon.
#
# .. note::
#
# The vertex for ``CLOSEPOLY`` is ignored, but we still need a placeholder
# in the ``verts`` array to keep the codes aligned with the vertices.
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.full(nverts, path.Path.LINETO)
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
n, _ = np.histogram(data, HIST_BINS)

###############################################################################
# To animate the histogram, we need an ``animate`` function, which generates
# a random set of numbers and updates the locations of the vertices for the
# histogram (in this case, only the heights of each rectangle). ``patch`` will
# eventually be a `.Patch` object.
patch = None
# a random set of numbers and updates the heights of rectanges. We utilize a
# python closure to track an instance of `.BarContainer` whose `.Rectangle`
# patches we shall update.


def animate(i):
# simulate new data coming in
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
return [patch, ]
def prepare_animation(bar_container):

def animate(frame_number):
# simulate new data coming in
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)
for count, rect in zip(n, bar_container.patches):
rect.set_height(count)
return bar_container.patches
return animate

###############################################################################
# And now we build the `.Path` and `.Patch` instances for the histogram using
# our vertices and codes. We add the patch to the `~.axes.Axes` instance, and
# setup the `.FuncAnimation` with our ``animate`` function.
fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
# Using :func:`~matplotlib.pyplot.hist` allows us to get an instance of
# `.BarContainer`, which is a collection of `.Rectangle` instances. Calling
# ``prepare_animation`` will define ``animate`` function working with supplied
# `.BarContainer`, all this is used to setup `.FuncAnimation`.

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,
ec="yellow", fc="green", alpha=0.5)
ax.set_ylim(top=55) # set safe limit to ensure that all data is visible.

ani = animation.FuncAnimation(fig, animate, 50, repeat=False, blit=True)
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,
repeat=False, blit=True)
plt.show()