Python绘制带自动缩放的线条、多边形和规则多边形集合图
对于前两个子图,我们将使用螺旋。它们的大小将在图形单位中设置,而不是数据单位。它们的位置将通过使用LineCollection和PolyCollection的offsets和offset_transform关键字参数在数据单位中设置。 第三个子图将生成规则多边形,其缩放和定位方式与前两个相同。 最后一个子情节说明了使用 offsets=(xo, yo),即单个元组而不是元组列表,来生成连续偏移的曲线,偏移量以数据单位给出。此行为仅适用于 LineCollection。 import matplotlib.pyplot as plt import numpy as np from matplotlib import collections, transforms nverts = 50 npts = 100 # 做一些螺旋 r = np.arange(nverts) theta = np.linspace(0, 2*np.pi, nverts) xx = r * np.sin(theta) yy = r * np.cos(theta) spiral = np.column_stack([xx, yy]) # 固定随机状态以实现可重复性 rs = np.random.RandomState(19680801) # 做一些偏移 xyo = rs.randn(npts, 2) # 列出颜色列表,依次循环使用默认系列 colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) fig.subplots_adjust(top=0.92, left=0.07, right=0.97, hspace=0.3, wspace=0.3) col = collections.LineCollection( [spiral], offsets=xyo, offset_transform=ax1.transData) trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0) col.set_transform(trans) # the points to pixels transform # 注意:集合初始化器的第一个参数必须是(x, y)元组序列的列表; 我们只有一个序列,但仍然必须将其放入列表中。 ax1.add_collection(col, autolim=True) # autolim=True 启用自动缩放。对于像这样有偏移的集合,它既不高效也不准确,但足以生成一个可用作起点的图。如果你事先知道想显示的 x 和 y 范围,最好明确设置它们,省略 *autolim* 关键字参数(或将其设置为 False),并且省略下面的 'ax1.autoscale_view()' 调用。 # 为线段创建一个变换,使它们的大小以点为单位给出: col.set_color(colors) ax1.autoscale_view() # See comment above, after ax1.add_collection. ax1.set_title('LineCollection using offsets') # 与上面相同的数据,但填充曲线 col = collections.PolyCollection( [spiral], offsets=xyo, offset_transform=ax2.transData) trans = transforms.Affine2D().scale(fig.dpi/72.0) col.set_transform(trans) # the points to pixels transform ax2.add_collection(col, autolim=True) col.set_color(colors) ax2.autoscale_view() ax2.set_title('PolyCollection using offsets') # 七边形正多边形 col = collections.RegularPolyCollection( 7, sizes=np.abs(xx) * 10.0, offsets=xyo, offset_transform=ax3.transData) trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) # the points to pixels transform ax3.add_collection(col, autolim=True) col.set_color(colors) ax3.autoscale_view() ax3.set_title('RegularPolyCollection using offsets') # 模拟一系列海洋洋流剖面,每次偏移0.1米/秒,这样它们就形成了有时称为“瀑布”图或“错落”图的效果。 nverts = 60 ncurves = 20 offs = (0.1, 0.0) yy = np.linspace(0, 2*np.pi, nverts) ym = np.max(yy) xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02*rs.randn(nverts) curve = np.column_stack([xxx, yy * 100]) segs.append(curve) col = collections.LineCollection(segs, offsets=offs) ax4.add_collection(col, autolim=True) col.set_color(colors) ax4.autoscale_view() ax4.set_title('Successive data offsets') ax4.set_xlabel('Zonal velocity component (m/s)') ax4.set_ylabel('Depth (m)') # 反转y轴,使深度向下增加 ax4.set_ylim(ax4.get_ylim()[::-1]) plt.show()参考文献:https://matplotlib.org/stable/gallery/shapes_and_collections/collections.html
