使用“矩形”和“多边形”构建直方图

使用路径补丁绘制矩形。 使用大量Rectangle实例的技术或使用PolyCollections的更快方法是在我们在mpl中使用moveto / lineto,closepoly等的正确路径之前实现的。 现在我们拥有它们,我们可以使用PathCollection更有效地绘制具有同质属性的常规形状对象的集合。 这个例子创建了一个直方图 - 在开始时设置顶点数组的工作量更大,但对于大量对象来说它应该更快。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.patches as patches
  4. import matplotlib.path as path
  5. fig, ax = plt.subplots()
  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, 50)
  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. # we need a (numrects x numsides x 2) numpy array for the path helper
  17. # function to build a compound path
  18. XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T
  19. # get the Path object
  20. barpath = path.Path.make_compound_path_from_polys(XY)
  21. # make a patch out of it
  22. patch = patches.PathPatch(barpath)
  23. ax.add_patch(patch)
  24. # update the view limits
  25. ax.set_xlim(left[0], right[-1])
  26. ax.set_ylim(bottom.min(), top.max())
  27. plt.show()

使用“矩形”和“多边形”构建直方图示例

应该注意的是,我们可以使用顶点和代码直接创建复合路径,而不是创建三维数组并使用make_compound_path_from_polys,如下所示

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

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.patches
  3. matplotlib.patches.PathPatch
  4. matplotlib.path
  5. matplotlib.path.Path
  6. matplotlib.path.Path.make_compound_path_from_polys
  7. matplotlib.axes.Axes.add_patch
  8. matplotlib.collections.PathCollection
  9. # This example shows an alternative to
  10. matplotlib.collections.PolyCollection
  11. matplotlib.axes.Axes.hist

下载这个示例