| 261 | return plt.gcf() |
| 262 | |
| 263 | def PyplotLinePolyCollection(): |
| 264 | import matplotlib.pyplot as plt |
| 265 | from matplotlib import collections, colors, transforms |
| 266 | import numpy as np |
| 267 | |
| 268 | nverts = 50 |
| 269 | npts = 100 |
| 270 | |
| 271 | # Make some spirals |
| 272 | r = np.arange(nverts) |
| 273 | theta = np.linspace(0, 2 * np.pi, nverts) |
| 274 | xx = r * np.sin(theta) |
| 275 | yy = r * np.cos(theta) |
| 276 | spiral = np.column_stack([xx, yy]) |
| 277 | |
| 278 | # Fixing random state for reproducibility |
| 279 | rs = np.random.RandomState(19680801) |
| 280 | |
| 281 | # Make some offsets |
| 282 | xyo = rs.randn(npts, 2) |
| 283 | |
| 284 | # Make a list of colors cycling through the default series. |
| 285 | colors = [colors.to_rgba(c) |
| 286 | for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] |
| 287 | |
| 288 | fig, axes = plt.subplots(2, 2) |
| 289 | fig.subplots_adjust(top=0.92, left=0.07, right=0.97, |
| 290 | hspace=0.3, wspace=0.3) |
| 291 | ((ax1, ax2), (ax3, ax4)) = axes # unpack the axes |
| 292 | |
| 293 | col = collections.LineCollection([spiral], offsets=xyo, |
| 294 | transOffset=ax1.transData) |
| 295 | trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0 / 72.0) |
| 296 | col.set_transform(trans) # the points to pixels transform |
| 297 | # Note: the first argument to the collection initializer |
| 298 | # must be a list of sequences of x,y tuples; we have only |
| 299 | # one sequence, but we still have to put it in a list. |
| 300 | ax1.add_collection(col, autolim=True) |
| 301 | # autolim=True enables autoscaling. For collections with |
| 302 | # offsets like this, it is neither efficient nor accurate, |
| 303 | # but it is good enough to generate a plot that you can use |
| 304 | # as a starting point. If you know beforehand the range of |
| 305 | # x and y that you want to show, it is better to set them |
| 306 | # explicitly, leave out the autolim kwarg (or set it to False), |
| 307 | # and omit the 'ax1.autoscale_view()' call below. |
| 308 | |
| 309 | # Make a transform for the line segments such that their size is |
| 310 | # given in points: |
| 311 | col.set_color(colors) |
| 312 | |
| 313 | ax1.autoscale_view() # See comment above, after ax1.add_collection. |
| 314 | ax1.set_title('LineCollection using offsets') |
| 315 | |
| 316 | # The same data as above, but fill the curves. |
| 317 | col = collections.PolyCollection([spiral], offsets=xyo, |
| 318 | transOffset=ax2.transData) |
| 319 | trans = transforms.Affine2D().scale(fig.dpi / 72.0) |
| 320 | col.set_transform(trans) # the points to pixels transform |