|
| 1 | +""" |
| 2 | +This example shows how to use a path patch to draw a bunch of |
| 3 | +rectangles for an animated histogram |
| 4 | +""" |
| 5 | +import time |
| 6 | +import numpy as np |
| 7 | +import matplotlib |
| 8 | +matplotlib.use('TkAgg') # do this before importing pylab |
| 9 | + |
| 10 | +import matplotlib.pyplot as plt |
| 11 | +import matplotlib.patches as patches |
| 12 | +import matplotlib.path as path |
| 13 | + |
| 14 | +fig = plt.figure() |
| 15 | +ax = fig.add_subplot(111) |
| 16 | + |
| 17 | +# histogram our data with numpy |
| 18 | +data = np.random.randn(1000) |
| 19 | +n, bins = np.histogram(data, 100) |
| 20 | + |
| 21 | +# get the corners of the rectangles for the histogram |
| 22 | +left = np.array(bins[:-1]) |
| 23 | +right = np.array(bins[1:]) |
| 24 | +bottom = np.zeros(len(left)) |
| 25 | +top = bottom + n |
| 26 | +nrects = len(left) |
| 27 | + |
| 28 | +# here comes the tricky part -- we have to set up the vertex and path |
| 29 | +# codes arrays using moveto, lineto and closepoly |
| 30 | + |
| 31 | +# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the |
| 32 | +# CLOSEPOLY; the vert for the closepoly is ignored but we still need |
| 33 | +# it to keep the codes aligned with the vertices |
| 34 | +nverts = nrects*(1+3+1) |
| 35 | +verts = np.zeros((nverts, 2)) |
| 36 | +codes = np.ones(nverts, int) * path.Path.LINETO |
| 37 | +codes[0::5] = path.Path.MOVETO |
| 38 | +codes[4::5] = path.Path.CLOSEPOLY |
| 39 | +verts[0::5,0] = left |
| 40 | +verts[0::5,1] = bottom |
| 41 | +verts[1::5,0] = left |
| 42 | +verts[1::5,1] = top |
| 43 | +verts[2::5,0] = right |
| 44 | +verts[2::5,1] = top |
| 45 | +verts[3::5,0] = right |
| 46 | +verts[3::5,1] = bottom |
| 47 | + |
| 48 | +barpath = path.Path(verts, codes) |
| 49 | +patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) |
| 50 | +ax.add_patch(patch) |
| 51 | + |
| 52 | +ax.set_xlim(left[0], right[-1]) |
| 53 | +ax.set_ylim(bottom.min(), top.max()) |
| 54 | + |
| 55 | +def animate(): |
| 56 | + if animate.cnt>=100: |
| 57 | + return |
| 58 | + |
| 59 | + animate.cnt += 1 |
| 60 | + # simulate new data coming in |
| 61 | + data = np.random.randn(1000) |
| 62 | + n, bins = np.histogram(data, 100) |
| 63 | + top = bottom + n |
| 64 | + verts[1::5,1] = top |
| 65 | + verts[2::5,1] = top |
| 66 | + fig.canvas.draw() |
| 67 | + fig.canvas.manager.window.after(100, animate) |
| 68 | +animate.cnt = 0 |
| 69 | +fig.canvas.manager.window.after(100, animate) |
| 70 | +plt.show() |
0 commit comments