使用“矩形”和“多边形”构建直方图
使用路径补丁绘制矩形。 使用大量Rectangle实例的技术或使用PolyCollections的更快方法是在我们在mpl中使用moveto / lineto,closepoly等的正确路径之前实现的。 现在我们拥有它们,我们可以使用PathCollection更有效地绘制具有同质属性的常规形状对象的集合。 这个例子创建了一个直方图 - 在开始时设置顶点数组的工作量更大,但对于大量对象来说它应该更快。
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport matplotlib.path as pathfig, ax = plt.subplots()# Fixing random state for reproducibilitynp.random.seed(19680801)# histogram our data with numpydata = np.random.randn(1000)n, bins = np.histogram(data, 50)# get the corners of the rectangles for the histogramleft = np.array(bins[:-1])right = np.array(bins[1:])bottom = np.zeros(len(left))top = bottom + n# we need a (numrects x numsides x 2) numpy array for the path helper# function to build a compound pathXY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T# get the Path objectbarpath = path.Path.make_compound_path_from_polys(XY)# make a patch out of itpatch = patches.PathPatch(barpath)ax.add_patch(patch)# update the view limitsax.set_xlim(left[0], right[-1])ax.set_ylim(bottom.min(), top.max())plt.show()

应该注意的是,我们可以使用顶点和代码直接创建复合路径,而不是创建三维数组并使用make_compound_path_from_polys,如下所示
nrects = len(left)nverts = nrects*(1+3+1)verts = np.zeros((nverts, 2))codes = np.ones(nverts, int) * path.Path.LINETOcodes[0::5] = path.Path.MOVETOcodes[4::5] = path.Path.CLOSEPOLYverts[0::5, 0] = leftverts[0::5, 1] = bottomverts[1::5, 0] = leftverts[1::5, 1] = topverts[2::5, 0] = rightverts[2::5, 1] = topverts[3::5, 0] = rightverts[3::5, 1] = bottombarpath = path.Path(verts, codes)
参考
此示例中显示了以下函数,方法,类和模块的使用:
import matplotlibmatplotlib.patchesmatplotlib.patches.PathPatchmatplotlib.pathmatplotlib.path.Pathmatplotlib.path.Path.make_compound_path_from_polysmatplotlib.axes.Axes.add_patchmatplotlib.collections.PathCollection# This example shows an alternative tomatplotlib.collections.PolyCollectionmatplotlib.axes.Axes.hist
