动画直方图

使用路径补丁为动画直方图绘制一堆矩形。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.patches as patches
  4. import matplotlib.path as path
  5. import matplotlib.animation as animation
  6. # Fixing random state for reproducibility
  7. np.random.seed(19680801)
  8. # histogram our data with numpy
  9. data = np.random.randn(1000)
  10. n, bins = np.histogram(data, 100)
  11. # get the corners of the rectangles for the histogram
  12. left = np.array(bins[:-1])
  13. right = np.array(bins[1:])
  14. bottom = np.zeros(len(left))
  15. top = bottom + n
  16. nrects = len(left)

这里有一个棘手的部分 - 我们必须为每个rect使用 plt.Path.MOVETOplt.Path.LINETOplt.Path.CLOSEPOLY设置顶点和路径代码数组。

  • 每个矩形我们需要1个 MOVETO,它设置了初始点。
  • 我们需要3个LINETO,它告诉Matplotlib从顶点1到顶点2,v2到v3和v3到v4绘制线。
  • 然后我们需要一个CLOSEPOLY,它告诉Matplotlib从v4到我们的初始顶点(MOVETO顶点)绘制一条线,以便关闭多边形。

注意:CLOSEPOLY的顶点被忽略,但我们仍然需要在verts数组中使用占位符来保持代码与顶点对齐。

  1. nverts = nrects * (1 + 3 + 1)
  2. verts = np.zeros((nverts, 2))
  3. codes = np.ones(nverts, int) * path.Path.LINETO
  4. codes[0::5] = path.Path.MOVETO
  5. codes[4::5] = path.Path.CLOSEPOLY
  6. verts[0::5, 0] = left
  7. verts[0::5, 1] = bottom
  8. verts[1::5, 0] = left
  9. verts[1::5, 1] = top
  10. verts[2::5, 0] = right
  11. verts[2::5, 1] = top
  12. verts[3::5, 0] = right
  13. verts[3::5, 1] = bottom

为了给直方图设置动画,我们需要一个动画函数,它生成一组随机数字并更新直方图顶点的位置(在这种情况下,只有每个矩形的高度)。 补丁最终将成为补丁对象。

  1. patch = None
  2. def animate(i):
  3. # simulate new data coming in
  4. data = np.random.randn(1000)
  5. n, bins = np.histogram(data, 100)
  6. top = bottom + n
  7. verts[1::5, 1] = top
  8. verts[2::5, 1] = top
  9. return [patch, ]

现在我们使用顶点和代码为直方图构建Path和Patch实例。 我们将补丁添加到Axes实例,并使用我们的animate函数设置FuncAnimation

  1. fig, ax = plt.subplots()
  2. barpath = path.Path(verts, codes)
  3. patch = patches.PathPatch(
  4. barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
  5. ax.add_patch(patch)
  6. ax.set_xlim(left[0], right[-1])
  7. ax.set_ylim(bottom.min(), top.max())
  8. ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)
  9. plt.show()

动画直方图示例

下载这个示例