动画柱状图

使用路径补丁为动画柱状图绘制一组矩形。

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)

# 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)

接下来是棘手的部分——我们必须使用 Path.MOVETOPath.LINETOPath.CLOSEPOLY 对于每个记录。

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

注解

顶点为 CLOSEPOLY 被忽略,但我们仍需要在 verts 数组以保持代码与顶点对齐。

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

为了使柱状图具有动画效果,我们需要 animate 函数,它生成一组随机数字并更新柱状图顶点的位置(在本例中,只更新每个矩形的高度)。 patch 最终将是一个 Patch 对象。

patch = None


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, ]

现在我们建立了 PathPatch 使用顶点和代码的柱状图实例。我们将补丁添加到 Axes 实例,并设置 FuncAnimation 与我们的 animate 功能。

fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
    barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())

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

脚本的总运行时间: (0分7.924秒)

关键词:matplotlib代码示例,codex,python plot,pyplot Gallery generated by Sphinx-Gallery