You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1200 lines
45 KiB

4 years ago
  1. """
  2. Support for plotting vector fields.
  3. Presently this contains Quiver and Barb. Quiver plots an arrow in the
  4. direction of the vector, with the size of the arrow related to the
  5. magnitude of the vector.
  6. Barbs are like quiver in that they point along a vector, but
  7. the magnitude of the vector is given schematically by the presence of barbs
  8. or flags on the barb.
  9. This will also become a home for things such as standard
  10. deviation ellipses, which can and will be derived very easily from
  11. the Quiver code.
  12. """
  13. import math
  14. import weakref
  15. import numpy as np
  16. from numpy import ma
  17. import matplotlib.collections as mcollections
  18. import matplotlib.transforms as transforms
  19. import matplotlib.text as mtext
  20. import matplotlib.artist as martist
  21. from matplotlib.artist import allow_rasterization
  22. from matplotlib import docstring
  23. import matplotlib.font_manager as font_manager
  24. from matplotlib.cbook import delete_masked_points
  25. from matplotlib.patches import CirclePolygon
  26. _quiver_doc = """
  27. Plot a 2-D field of arrows.
  28. Call signatures::
  29. quiver(U, V, **kw)
  30. quiver(U, V, C, **kw)
  31. quiver(X, Y, U, V, **kw)
  32. quiver(X, Y, U, V, C, **kw)
  33. *U* and *V* are the arrow data, *X* and *Y* set the location of the
  34. arrows, and *C* sets the color of the arrows. These arguments may be 1-D or
  35. 2-D arrays or sequences.
  36. If *X* and *Y* are absent, they will be generated as a uniform grid.
  37. If *U* and *V* are 2-D arrays and *X* and *Y* are 1-D, and if ``len(X)`` and
  38. ``len(Y)`` match the column and row dimensions of *U*, then *X* and *Y* will be
  39. expanded with :func:`numpy.meshgrid`.
  40. The default settings auto-scales the length of the arrows to a reasonable size.
  41. To change this behavior see the *scale* and *scale_units* kwargs.
  42. The defaults give a slightly swept-back arrow; to make the head a
  43. triangle, make *headaxislength* the same as *headlength*. To make the
  44. arrow more pointed, reduce *headwidth* or increase *headlength* and
  45. *headaxislength*. To make the head smaller relative to the shaft,
  46. scale down all the head parameters. You will probably do best to leave
  47. minshaft alone.
  48. *linewidths* and *edgecolors* can be used to customize the arrow
  49. outlines.
  50. Parameters
  51. ----------
  52. X : 1D or 2D array, sequence, optional
  53. The x coordinates of the arrow locations
  54. Y : 1D or 2D array, sequence, optional
  55. The y coordinates of the arrow locations
  56. U : 1D or 2D array or masked array, sequence
  57. The x components of the arrow vectors
  58. V : 1D or 2D array or masked array, sequence
  59. The y components of the arrow vectors
  60. C : 1D or 2D array, sequence, optional
  61. The arrow colors
  62. units : [ 'width' | 'height' | 'dots' | 'inches' | 'x' | 'y' | 'xy' ]
  63. The arrow dimensions (except for *length*) are measured in multiples of
  64. this unit.
  65. 'width' or 'height': the width or height of the axis
  66. 'dots' or 'inches': pixels or inches, based on the figure dpi
  67. 'x', 'y', or 'xy': respectively *X*, *Y*, or :math:`\\sqrt{X^2 + Y^2}`
  68. in data units
  69. The arrows scale differently depending on the units. For
  70. 'x' or 'y', the arrows get larger as one zooms in; for other
  71. units, the arrow size is independent of the zoom state. For
  72. 'width or 'height', the arrow size increases with the width and
  73. height of the axes, respectively, when the window is resized;
  74. for 'dots' or 'inches', resizing does not change the arrows.
  75. angles : [ 'uv' | 'xy' ], array, optional
  76. Method for determining the angle of the arrows. Default is 'uv'.
  77. 'uv': the arrow axis aspect ratio is 1 so that
  78. if *U*==*V* the orientation of the arrow on the plot is 45 degrees
  79. counter-clockwise from the horizontal axis (positive to the right).
  80. 'xy': arrows point from (x,y) to (x+u, y+v).
  81. Use this for plotting a gradient field, for example.
  82. Alternatively, arbitrary angles may be specified as an array
  83. of values in degrees, counter-clockwise from the horizontal axis.
  84. Note: inverting a data axis will correspondingly invert the
  85. arrows only with ``angles='xy'``.
  86. scale : None, float, optional
  87. Number of data units per arrow length unit, e.g., m/s per plot width; a
  88. smaller scale parameter makes the arrow longer. Default is *None*.
  89. If *None*, a simple autoscaling algorithm is used, based on the average
  90. vector length and the number of vectors. The arrow length unit is given by
  91. the *scale_units* parameter
  92. scale_units : [ 'width' | 'height' | 'dots' | 'inches' | 'x' | 'y' | 'xy' ], \
  93. None, optional
  94. If the *scale* kwarg is *None*, the arrow length unit. Default is *None*.
  95. e.g. *scale_units* is 'inches', *scale* is 2.0, and
  96. ``(u,v) = (1,0)``, then the vector will be 0.5 inches long.
  97. If *scale_units* is 'width'/'height', then the vector will be half the
  98. width/height of the axes.
  99. If *scale_units* is 'x' then the vector will be 0.5 x-axis
  100. units. To plot vectors in the x-y plane, with u and v having
  101. the same units as x and y, use
  102. ``angles='xy', scale_units='xy', scale=1``.
  103. width : scalar, optional
  104. Shaft width in arrow units; default depends on choice of units,
  105. above, and number of vectors; a typical starting value is about
  106. 0.005 times the width of the plot.
  107. headwidth : scalar, optional
  108. Head width as multiple of shaft width, default is 3
  109. headlength : scalar, optional
  110. Head length as multiple of shaft width, default is 5
  111. headaxislength : scalar, optional
  112. Head length at shaft intersection, default is 4.5
  113. minshaft : scalar, optional
  114. Length below which arrow scales, in units of head length. Do not
  115. set this to less than 1, or small arrows will look terrible!
  116. Default is 1
  117. minlength : scalar, optional
  118. Minimum length as a multiple of shaft width; if an arrow length
  119. is less than this, plot a dot (hexagon) of this diameter instead.
  120. Default is 1.
  121. pivot : [ 'tail' | 'mid' | 'middle' | 'tip' ], optional
  122. The part of the arrow that is at the grid point; the arrow rotates
  123. about this point, hence the name *pivot*.
  124. color : [ color | color sequence ], optional
  125. This is a synonym for the
  126. :class:`~matplotlib.collections.PolyCollection` facecolor kwarg.
  127. If *C* has been set, *color* has no effect.
  128. Notes
  129. -----
  130. Additional :class:`~matplotlib.collections.PolyCollection`
  131. keyword arguments:
  132. %(PolyCollection)s
  133. See Also
  134. --------
  135. quiverkey : Add a key to a quiver plot
  136. """ % docstring.interpd.params
  137. _quiverkey_doc = """
  138. Add a key to a quiver plot.
  139. Call signature::
  140. quiverkey(Q, X, Y, U, label, **kw)
  141. Arguments:
  142. *Q*:
  143. The Quiver instance returned by a call to quiver.
  144. *X*, *Y*:
  145. The location of the key; additional explanation follows.
  146. *U*:
  147. The length of the key
  148. *label*:
  149. A string with the length and units of the key
  150. Keyword arguments:
  151. *angle* = 0
  152. The angle of the key arrow. Measured in degrees anti-clockwise from the
  153. x-axis.
  154. *coordinates* = [ 'axes' | 'figure' | 'data' | 'inches' ]
  155. Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are
  156. normalized coordinate systems with 0,0 in the lower left and 1,1
  157. in the upper right; 'data' are the axes data coordinates (used for
  158. the locations of the vectors in the quiver plot itself); 'inches'
  159. is position in the figure in inches, with 0,0 at the lower left
  160. corner.
  161. *color*:
  162. overrides face and edge colors from *Q*.
  163. *labelpos* = [ 'N' | 'S' | 'E' | 'W' ]
  164. Position the label above, below, to the right, to the left of the
  165. arrow, respectively.
  166. *labelsep*:
  167. Distance in inches between the arrow and the label. Default is
  168. 0.1
  169. *labelcolor*:
  170. defaults to default :class:`~matplotlib.text.Text` color.
  171. *fontproperties*:
  172. A dictionary with keyword arguments accepted by the
  173. :class:`~matplotlib.font_manager.FontProperties` initializer:
  174. *family*, *style*, *variant*, *size*, *weight*
  175. Any additional keyword arguments are used to override vector
  176. properties taken from *Q*.
  177. The positioning of the key depends on *X*, *Y*, *coordinates*, and
  178. *labelpos*. If *labelpos* is 'N' or 'S', *X*, *Y* give the position
  179. of the middle of the key arrow. If *labelpos* is 'E', *X*, *Y*
  180. positions the head, and if *labelpos* is 'W', *X*, *Y* positions the
  181. tail; in either of these two cases, *X*, *Y* is somewhere in the
  182. middle of the arrow+label key object.
  183. """
  184. class QuiverKey(martist.Artist):
  185. """ Labelled arrow for use as a quiver plot scale key."""
  186. halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'}
  187. valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'}
  188. pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'}
  189. def __init__(self, Q, X, Y, U, label,
  190. *, angle=0, coordinates='axes', color=None, labelsep=0.1,
  191. labelpos='N', labelcolor=None, fontproperties=None,
  192. **kw):
  193. martist.Artist.__init__(self)
  194. self.Q = Q
  195. self.X = X
  196. self.Y = Y
  197. self.U = U
  198. self.angle = angle
  199. self.coord = coordinates
  200. self.color = color
  201. self.label = label
  202. self._labelsep_inches = labelsep
  203. self.labelsep = (self._labelsep_inches * Q.ax.figure.dpi)
  204. # try to prevent closure over the real self
  205. weak_self = weakref.ref(self)
  206. def on_dpi_change(fig):
  207. self_weakref = weak_self()
  208. if self_weakref is not None:
  209. self_weakref.labelsep = (self_weakref._labelsep_inches*fig.dpi)
  210. self_weakref._initialized = False # simple brute force update
  211. # works because _init is
  212. # called at the start of
  213. # draw.
  214. self._cid = Q.ax.figure.callbacks.connect('dpi_changed',
  215. on_dpi_change)
  216. self.labelpos = labelpos
  217. self.labelcolor = labelcolor
  218. self.fontproperties = fontproperties or dict()
  219. self.kw = kw
  220. _fp = self.fontproperties
  221. # boxprops = dict(facecolor='red')
  222. self.text = mtext.Text(
  223. text=label, # bbox=boxprops,
  224. horizontalalignment=self.halign[self.labelpos],
  225. verticalalignment=self.valign[self.labelpos],
  226. fontproperties=font_manager.FontProperties(**_fp))
  227. if self.labelcolor is not None:
  228. self.text.set_color(self.labelcolor)
  229. self._initialized = False
  230. self.zorder = Q.zorder + 0.1
  231. def remove(self):
  232. """
  233. Overload the remove method
  234. """
  235. self.Q.ax.figure.callbacks.disconnect(self._cid)
  236. self._cid = None
  237. # pass the remove call up the stack
  238. martist.Artist.remove(self)
  239. __init__.__doc__ = _quiverkey_doc
  240. def _init(self):
  241. if True: # not self._initialized:
  242. if not self.Q._initialized:
  243. self.Q._init()
  244. self._set_transform()
  245. _pivot = self.Q.pivot
  246. self.Q.pivot = self.pivot[self.labelpos]
  247. # Hack: save and restore the Umask
  248. _mask = self.Q.Umask
  249. self.Q.Umask = ma.nomask
  250. self.verts = self.Q._make_verts(np.array([self.U]),
  251. np.zeros((1,)),
  252. self.angle)
  253. self.Q.Umask = _mask
  254. self.Q.pivot = _pivot
  255. kw = self.Q.polykw
  256. kw.update(self.kw)
  257. self.vector = mcollections.PolyCollection(
  258. self.verts,
  259. offsets=[(self.X, self.Y)],
  260. transOffset=self.get_transform(),
  261. **kw)
  262. if self.color is not None:
  263. self.vector.set_color(self.color)
  264. self.vector.set_transform(self.Q.get_transform())
  265. self.vector.set_figure(self.get_figure())
  266. self._initialized = True
  267. def _text_x(self, x):
  268. if self.labelpos == 'E':
  269. return x + self.labelsep
  270. elif self.labelpos == 'W':
  271. return x - self.labelsep
  272. else:
  273. return x
  274. def _text_y(self, y):
  275. if self.labelpos == 'N':
  276. return y + self.labelsep
  277. elif self.labelpos == 'S':
  278. return y - self.labelsep
  279. else:
  280. return y
  281. @allow_rasterization
  282. def draw(self, renderer):
  283. self._init()
  284. self.vector.draw(renderer)
  285. x, y = self.get_transform().transform_point((self.X, self.Y))
  286. self.text.set_x(self._text_x(x))
  287. self.text.set_y(self._text_y(y))
  288. self.text.draw(renderer)
  289. self.stale = False
  290. def _set_transform(self):
  291. if self.coord == 'data':
  292. self.set_transform(self.Q.ax.transData)
  293. elif self.coord == 'axes':
  294. self.set_transform(self.Q.ax.transAxes)
  295. elif self.coord == 'figure':
  296. self.set_transform(self.Q.ax.figure.transFigure)
  297. elif self.coord == 'inches':
  298. self.set_transform(self.Q.ax.figure.dpi_scale_trans)
  299. else:
  300. raise ValueError('unrecognized coordinates')
  301. def set_figure(self, fig):
  302. martist.Artist.set_figure(self, fig)
  303. self.text.set_figure(fig)
  304. def contains(self, mouseevent):
  305. # Maybe the dictionary should allow one to
  306. # distinguish between a text hit and a vector hit.
  307. if (self.text.contains(mouseevent)[0] or
  308. self.vector.contains(mouseevent)[0]):
  309. return True, {}
  310. return False, {}
  311. quiverkey_doc = _quiverkey_doc
  312. # This is a helper function that parses out the various combination of
  313. # arguments for doing colored vector plots. Pulling it out here
  314. # allows both Quiver and Barbs to use it
  315. def _parse_args(*args):
  316. X, Y, U, V, C = [None] * 5
  317. args = list(args)
  318. # The use of atleast_1d allows for handling scalar arguments while also
  319. # keeping masked arrays
  320. if len(args) == 3 or len(args) == 5:
  321. C = np.atleast_1d(args.pop(-1))
  322. V = np.atleast_1d(args.pop(-1))
  323. U = np.atleast_1d(args.pop(-1))
  324. if U.ndim == 1:
  325. nr, nc = 1, U.shape[0]
  326. else:
  327. nr, nc = U.shape
  328. if len(args) == 2: # remaining after removing U,V,C
  329. X, Y = [np.array(a).ravel() for a in args]
  330. if len(X) == nc and len(Y) == nr:
  331. X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
  332. else:
  333. indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
  334. X, Y = [np.ravel(a) for a in indexgrid]
  335. return X, Y, U, V, C
  336. def _check_consistent_shapes(*arrays):
  337. all_shapes = {a.shape for a in arrays}
  338. if len(all_shapes) != 1:
  339. raise ValueError('The shapes of the passed in arrays do not match')
  340. class Quiver(mcollections.PolyCollection):
  341. """
  342. Specialized PolyCollection for arrows.
  343. The only API method is set_UVC(), which can be used
  344. to change the size, orientation, and color of the
  345. arrows; their locations are fixed when the class is
  346. instantiated. Possibly this method will be useful
  347. in animations.
  348. Much of the work in this class is done in the draw()
  349. method so that as much information as possible is available
  350. about the plot. In subsequent draw() calls, recalculation
  351. is limited to things that might have changed, so there
  352. should be no performance penalty from putting the calculations
  353. in the draw() method.
  354. """
  355. _PIVOT_VALS = ('tail', 'middle', 'tip')
  356. @docstring.Substitution(_quiver_doc)
  357. def __init__(self, ax, *args,
  358. scale=None, headwidth=3, headlength=5, headaxislength=4.5,
  359. minshaft=1, minlength=1, units='width', scale_units=None,
  360. angles='uv', width=None, color='k', pivot='tail', **kw):
  361. """
  362. The constructor takes one required argument, an Axes
  363. instance, followed by the args and kwargs described
  364. by the following pyplot interface documentation:
  365. %s
  366. """
  367. self.ax = ax
  368. X, Y, U, V, C = _parse_args(*args)
  369. self.X = X
  370. self.Y = Y
  371. self.XY = np.column_stack((X, Y))
  372. self.N = len(X)
  373. self.scale = scale
  374. self.headwidth = headwidth
  375. self.headlength = float(headlength)
  376. self.headaxislength = headaxislength
  377. self.minshaft = minshaft
  378. self.minlength = minlength
  379. self.units = units
  380. self.scale_units = scale_units
  381. self.angles = angles
  382. self.width = width
  383. self.color = color
  384. if pivot.lower() == 'mid':
  385. pivot = 'middle'
  386. self.pivot = pivot.lower()
  387. if self.pivot not in self._PIVOT_VALS:
  388. raise ValueError(
  389. 'pivot must be one of {keys}, you passed {inp}'.format(
  390. keys=self._PIVOT_VALS, inp=pivot))
  391. self.transform = kw.pop('transform', ax.transData)
  392. kw.setdefault('facecolors', self.color)
  393. kw.setdefault('linewidths', (0,))
  394. mcollections.PolyCollection.__init__(self, [], offsets=self.XY,
  395. transOffset=self.transform,
  396. closed=False,
  397. **kw)
  398. self.polykw = kw
  399. self.set_UVC(U, V, C)
  400. self._initialized = False
  401. self.keyvec = None
  402. self.keytext = None
  403. # try to prevent closure over the real self
  404. weak_self = weakref.ref(self)
  405. def on_dpi_change(fig):
  406. self_weakref = weak_self()
  407. if self_weakref is not None:
  408. self_weakref._new_UV = True # vertices depend on width, span
  409. # which in turn depend on dpi
  410. self_weakref._initialized = False # simple brute force update
  411. # works because _init is
  412. # called at the start of
  413. # draw.
  414. self._cid = self.ax.figure.callbacks.connect('dpi_changed',
  415. on_dpi_change)
  416. def remove(self):
  417. """
  418. Overload the remove method
  419. """
  420. # disconnect the call back
  421. self.ax.figure.callbacks.disconnect(self._cid)
  422. self._cid = None
  423. # pass the remove call up the stack
  424. mcollections.PolyCollection.remove(self)
  425. def _init(self):
  426. """
  427. Initialization delayed until first draw;
  428. allow time for axes setup.
  429. """
  430. # It seems that there are not enough event notifications
  431. # available to have this work on an as-needed basis at present.
  432. if True: # not self._initialized:
  433. trans = self._set_transform()
  434. ax = self.ax
  435. sx, sy = trans.inverted().transform_point(
  436. (ax.bbox.width, ax.bbox.height))
  437. self.span = sx
  438. if self.width is None:
  439. sn = np.clip(math.sqrt(self.N), 8, 25)
  440. self.width = 0.06 * self.span / sn
  441. # _make_verts sets self.scale if not already specified
  442. if not self._initialized and self.scale is None:
  443. self._make_verts(self.U, self.V, self.angles)
  444. self._initialized = True
  445. def get_datalim(self, transData):
  446. trans = self.get_transform()
  447. transOffset = self.get_offset_transform()
  448. full_transform = (trans - transData) + (transOffset - transData)
  449. XY = full_transform.transform(self.XY)
  450. bbox = transforms.Bbox.null()
  451. bbox.update_from_data_xy(XY, ignore=True)
  452. return bbox
  453. @allow_rasterization
  454. def draw(self, renderer):
  455. self._init()
  456. verts = self._make_verts(self.U, self.V, self.angles)
  457. self.set_verts(verts, closed=False)
  458. self._new_UV = False
  459. mcollections.PolyCollection.draw(self, renderer)
  460. self.stale = False
  461. def set_UVC(self, U, V, C=None):
  462. # We need to ensure we have a copy, not a reference
  463. # to an array that might change before draw().
  464. U = ma.masked_invalid(U, copy=True).ravel()
  465. V = ma.masked_invalid(V, copy=True).ravel()
  466. mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True)
  467. if C is not None:
  468. C = ma.masked_invalid(C, copy=True).ravel()
  469. mask = ma.mask_or(mask, C.mask, copy=False, shrink=True)
  470. if mask is ma.nomask:
  471. C = C.filled()
  472. else:
  473. C = ma.array(C, mask=mask, copy=False)
  474. self.U = U.filled(1)
  475. self.V = V.filled(1)
  476. self.Umask = mask
  477. if C is not None:
  478. self.set_array(C)
  479. self._new_UV = True
  480. self.stale = True
  481. def _dots_per_unit(self, units):
  482. """
  483. Return a scale factor for converting from units to pixels
  484. """
  485. ax = self.ax
  486. if units in ('x', 'y', 'xy'):
  487. if units == 'x':
  488. dx0 = ax.viewLim.width
  489. dx1 = ax.bbox.width
  490. elif units == 'y':
  491. dx0 = ax.viewLim.height
  492. dx1 = ax.bbox.height
  493. else: # 'xy' is assumed
  494. dxx0 = ax.viewLim.width
  495. dxx1 = ax.bbox.width
  496. dyy0 = ax.viewLim.height
  497. dyy1 = ax.bbox.height
  498. dx1 = np.hypot(dxx1, dyy1)
  499. dx0 = np.hypot(dxx0, dyy0)
  500. dx = dx1 / dx0
  501. else:
  502. if units == 'width':
  503. dx = ax.bbox.width
  504. elif units == 'height':
  505. dx = ax.bbox.height
  506. elif units == 'dots':
  507. dx = 1.0
  508. elif units == 'inches':
  509. dx = ax.figure.dpi
  510. else:
  511. raise ValueError('unrecognized units')
  512. return dx
  513. def _set_transform(self):
  514. """
  515. Sets the PolygonCollection transform to go
  516. from arrow width units to pixels.
  517. """
  518. dx = self._dots_per_unit(self.units)
  519. self._trans_scale = dx # pixels per arrow width unit
  520. trans = transforms.Affine2D().scale(dx)
  521. self.set_transform(trans)
  522. return trans
  523. def _angles_lengths(self, U, V, eps=1):
  524. xy = self.ax.transData.transform(self.XY)
  525. uv = np.column_stack((U, V))
  526. xyp = self.ax.transData.transform(self.XY + eps * uv)
  527. dxy = xyp - xy
  528. angles = np.arctan2(dxy[:, 1], dxy[:, 0])
  529. lengths = np.hypot(*dxy.T) / eps
  530. return angles, lengths
  531. def _make_verts(self, U, V, angles):
  532. uv = (U + V * 1j)
  533. str_angles = angles if isinstance(angles, str) else ''
  534. if str_angles == 'xy' and self.scale_units == 'xy':
  535. # Here eps is 1 so that if we get U, V by diffing
  536. # the X, Y arrays, the vectors will connect the
  537. # points, regardless of the axis scaling (including log).
  538. angles, lengths = self._angles_lengths(U, V, eps=1)
  539. elif str_angles == 'xy' or self.scale_units == 'xy':
  540. # Calculate eps based on the extents of the plot
  541. # so that we don't end up with roundoff error from
  542. # adding a small number to a large.
  543. eps = np.abs(self.ax.dataLim.extents).max() * 0.001
  544. angles, lengths = self._angles_lengths(U, V, eps=eps)
  545. if str_angles and self.scale_units == 'xy':
  546. a = lengths
  547. else:
  548. a = np.abs(uv)
  549. if self.scale is None:
  550. sn = max(10, math.sqrt(self.N))
  551. if self.Umask is not ma.nomask:
  552. amean = a[~self.Umask].mean()
  553. else:
  554. amean = a.mean()
  555. # crude auto-scaling
  556. # scale is typical arrow length as a multiple of the arrow width
  557. scale = 1.8 * amean * sn / self.span
  558. if self.scale_units is None:
  559. if self.scale is None:
  560. self.scale = scale
  561. widthu_per_lenu = 1.0
  562. else:
  563. if self.scale_units == 'xy':
  564. dx = 1
  565. else:
  566. dx = self._dots_per_unit(self.scale_units)
  567. widthu_per_lenu = dx / self._trans_scale
  568. if self.scale is None:
  569. self.scale = scale * widthu_per_lenu
  570. length = a * (widthu_per_lenu / (self.scale * self.width))
  571. X, Y = self._h_arrows(length)
  572. if str_angles == 'xy':
  573. theta = angles
  574. elif str_angles == 'uv':
  575. theta = np.angle(uv)
  576. else:
  577. theta = ma.masked_invalid(np.deg2rad(angles)).filled(0)
  578. theta = theta.reshape((-1, 1)) # for broadcasting
  579. xy = (X + Y * 1j) * np.exp(1j * theta) * self.width
  580. XY = np.stack((xy.real, xy.imag), axis=2)
  581. if self.Umask is not ma.nomask:
  582. XY = ma.array(XY)
  583. XY[self.Umask] = ma.masked
  584. # This might be handled more efficiently with nans, given
  585. # that nans will end up in the paths anyway.
  586. return XY
  587. def _h_arrows(self, length):
  588. """ length is in arrow width units """
  589. # It might be possible to streamline the code
  590. # and speed it up a bit by using complex (x,y)
  591. # instead of separate arrays; but any gain would be slight.
  592. minsh = self.minshaft * self.headlength
  593. N = len(length)
  594. length = length.reshape(N, 1)
  595. # This number is chosen based on when pixel values overflow in Agg
  596. # causing rendering errors
  597. # length = np.minimum(length, 2 ** 16)
  598. np.clip(length, 0, 2 ** 16, out=length)
  599. # x, y: normal horizontal arrow
  600. x = np.array([0, -self.headaxislength,
  601. -self.headlength, 0],
  602. np.float64)
  603. x = x + np.array([0, 1, 1, 1]) * length
  604. y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
  605. y = np.repeat(y[np.newaxis, :], N, axis=0)
  606. # x0, y0: arrow without shaft, for short vectors
  607. x0 = np.array([0, minsh - self.headaxislength,
  608. minsh - self.headlength, minsh], np.float64)
  609. y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
  610. ii = [0, 1, 2, 3, 2, 1, 0, 0]
  611. X = x.take(ii, 1)
  612. Y = y.take(ii, 1)
  613. Y[:, 3:-1] *= -1
  614. X0 = x0.take(ii)
  615. Y0 = y0.take(ii)
  616. Y0[3:-1] *= -1
  617. shrink = length / minsh if minsh != 0. else 0.
  618. X0 = shrink * X0[np.newaxis, :]
  619. Y0 = shrink * Y0[np.newaxis, :]
  620. short = np.repeat(length < minsh, 8, axis=1)
  621. # Now select X0, Y0 if short, otherwise X, Y
  622. np.copyto(X, X0, where=short)
  623. np.copyto(Y, Y0, where=short)
  624. if self.pivot == 'middle':
  625. X -= 0.5 * X[:, 3, np.newaxis]
  626. elif self.pivot == 'tip':
  627. X = X - X[:, 3, np.newaxis] # numpy bug? using -= does not
  628. # work here unless we multiply
  629. # by a float first, as with 'mid'.
  630. elif self.pivot != 'tail':
  631. raise ValueError(("Quiver.pivot must have value in {{'middle', "
  632. "'tip', 'tail'}} not {0}").format(self.pivot))
  633. tooshort = length < self.minlength
  634. if tooshort.any():
  635. # Use a heptagonal dot:
  636. th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0)
  637. x1 = np.cos(th) * self.minlength * 0.5
  638. y1 = np.sin(th) * self.minlength * 0.5
  639. X1 = np.repeat(x1[np.newaxis, :], N, axis=0)
  640. Y1 = np.repeat(y1[np.newaxis, :], N, axis=0)
  641. tooshort = np.repeat(tooshort, 8, 1)
  642. np.copyto(X, X1, where=tooshort)
  643. np.copyto(Y, Y1, where=tooshort)
  644. # Mask handling is deferred to the caller, _make_verts.
  645. return X, Y
  646. quiver_doc = _quiver_doc
  647. _barbs_doc = r"""
  648. Plot a 2-D field of barbs.
  649. Call signatures::
  650. barb(U, V, **kw)
  651. barb(U, V, C, **kw)
  652. barb(X, Y, U, V, **kw)
  653. barb(X, Y, U, V, C, **kw)
  654. Arguments:
  655. *X*, *Y*:
  656. The x and y coordinates of the barb locations
  657. (default is head of barb; see *pivot* kwarg)
  658. *U*, *V*:
  659. Give the x and y components of the barb shaft
  660. *C*:
  661. An optional array used to map colors to the barbs
  662. All arguments may be 1-D or 2-D arrays or sequences. If *X* and *Y*
  663. are absent, they will be generated as a uniform grid. If *U* and *V*
  664. are 2-D arrays but *X* and *Y* are 1-D, and if ``len(X)`` and ``len(Y)``
  665. match the column and row dimensions of *U*, then *X* and *Y* will be
  666. expanded with :func:`numpy.meshgrid`.
  667. *U*, *V*, *C* may be masked arrays, but masked *X*, *Y* are not
  668. supported at present.
  669. Keyword arguments:
  670. *length*:
  671. Length of the barb in points; the other parts of the barb
  672. are scaled against this.
  673. Default is 7.
  674. *pivot*: [ 'tip' | 'middle' | float ]
  675. The part of the arrow that is at the grid point; the arrow rotates
  676. about this point, hence the name *pivot*. Default is 'tip'. Can
  677. also be a number, which shifts the start of the barb that many
  678. points from the origin.
  679. *barbcolor*: [ color | color sequence ]
  680. Specifies the color all parts of the barb except any flags. This
  681. parameter is analogous to the *edgecolor* parameter for polygons,
  682. which can be used instead. However this parameter will override
  683. facecolor.
  684. *flagcolor*: [ color | color sequence ]
  685. Specifies the color of any flags on the barb. This parameter is
  686. analogous to the *facecolor* parameter for polygons, which can be
  687. used instead. However this parameter will override facecolor. If
  688. this is not set (and *C* has not either) then *flagcolor* will be
  689. set to match *barbcolor* so that the barb has a uniform color. If
  690. *C* has been set, *flagcolor* has no effect.
  691. *sizes*:
  692. A dictionary of coefficients specifying the ratio of a given
  693. feature to the length of the barb. Only those values one wishes to
  694. override need to be included. These features include:
  695. - 'spacing' - space between features (flags, full/half barbs)
  696. - 'height' - height (distance from shaft to top) of a flag or
  697. full barb
  698. - 'width' - width of a flag, twice the width of a full barb
  699. - 'emptybarb' - radius of the circle used for low magnitudes
  700. *fill_empty*:
  701. A flag on whether the empty barbs (circles) that are drawn should
  702. be filled with the flag color. If they are not filled, they will
  703. be drawn such that no color is applied to the center. Default is
  704. False
  705. *rounding*:
  706. A flag to indicate whether the vector magnitude should be rounded
  707. when allocating barb components. If True, the magnitude is
  708. rounded to the nearest multiple of the half-barb increment. If
  709. False, the magnitude is simply truncated to the next lowest
  710. multiple. Default is True
  711. *barb_increments*:
  712. A dictionary of increments specifying values to associate with
  713. different parts of the barb. Only those values one wishes to
  714. override need to be included.
  715. - 'half' - half barbs (Default is 5)
  716. - 'full' - full barbs (Default is 10)
  717. - 'flag' - flags (default is 50)
  718. *flip_barb*:
  719. Either a single boolean flag or an array of booleans. Single
  720. boolean indicates whether the lines and flags should point
  721. opposite to normal for all barbs. An array (which should be the
  722. same size as the other data arrays) indicates whether to flip for
  723. each individual barb. Normal behavior is for the barbs and lines
  724. to point right (comes from wind barbs having these features point
  725. towards low pressure in the Northern Hemisphere.) Default is
  726. False
  727. Barbs are traditionally used in meteorology as a way to plot the speed
  728. and direction of wind observations, but can technically be used to
  729. plot any two dimensional vector quantity. As opposed to arrows, which
  730. give vector magnitude by the length of the arrow, the barbs give more
  731. quantitative information about the vector magnitude by putting slanted
  732. lines or a triangle for various increments in magnitude, as show
  733. schematically below::
  734. : /\ \\
  735. : / \ \\
  736. : / \ \ \\
  737. : / \ \ \\
  738. : ------------------------------
  739. .. note the double \\ at the end of each line to make the figure
  740. .. render correctly
  741. The largest increment is given by a triangle (or "flag"). After those
  742. come full lines (barbs). The smallest increment is a half line. There
  743. is only, of course, ever at most 1 half line. If the magnitude is
  744. small and only needs a single half-line and no full lines or
  745. triangles, the half-line is offset from the end of the barb so that it
  746. can be easily distinguished from barbs with a single full line. The
  747. magnitude for the barb shown above would nominally be 65, using the
  748. standard increments of 50, 10, and 5.
  749. linewidths and edgecolors can be used to customize the barb.
  750. Additional :class:`~matplotlib.collections.PolyCollection` keyword
  751. arguments:
  752. %(PolyCollection)s
  753. """ % docstring.interpd.params
  754. docstring.interpd.update(barbs_doc=_barbs_doc)
  755. class Barbs(mcollections.PolyCollection):
  756. '''
  757. Specialized PolyCollection for barbs.
  758. The only API method is :meth:`set_UVC`, which can be used to
  759. change the size, orientation, and color of the arrows. Locations
  760. are changed using the :meth:`set_offsets` collection method.
  761. Possibly this method will be useful in animations.
  762. There is one internal function :meth:`_find_tails` which finds
  763. exactly what should be put on the barb given the vector magnitude.
  764. From there :meth:`_make_barbs` is used to find the vertices of the
  765. polygon to represent the barb based on this information.
  766. '''
  767. # This may be an abuse of polygons here to render what is essentially maybe
  768. # 1 triangle and a series of lines. It works fine as far as I can tell
  769. # however.
  770. @docstring.interpd
  771. def __init__(self, ax, *args,
  772. pivot='tip', length=7, barbcolor=None, flagcolor=None,
  773. sizes=None, fill_empty=False, barb_increments=None,
  774. rounding=True, flip_barb=False, **kw):
  775. """
  776. The constructor takes one required argument, an Axes
  777. instance, followed by the args and kwargs described
  778. by the following pyplot interface documentation:
  779. %(barbs_doc)s
  780. """
  781. self.sizes = sizes or dict()
  782. self.fill_empty = fill_empty
  783. self.barb_increments = barb_increments or dict()
  784. self.rounding = rounding
  785. self.flip = flip_barb
  786. transform = kw.pop('transform', ax.transData)
  787. self._pivot = pivot
  788. self._length = length
  789. barbcolor = barbcolor
  790. flagcolor = flagcolor
  791. # Flagcolor and barbcolor provide convenience parameters for
  792. # setting the facecolor and edgecolor, respectively, of the barb
  793. # polygon. We also work here to make the flag the same color as the
  794. # rest of the barb by default
  795. if None in (barbcolor, flagcolor):
  796. kw['edgecolors'] = 'face'
  797. if flagcolor:
  798. kw['facecolors'] = flagcolor
  799. elif barbcolor:
  800. kw['facecolors'] = barbcolor
  801. else:
  802. # Set to facecolor passed in or default to black
  803. kw.setdefault('facecolors', 'k')
  804. else:
  805. kw['edgecolors'] = barbcolor
  806. kw['facecolors'] = flagcolor
  807. # Explicitly set a line width if we're not given one, otherwise
  808. # polygons are not outlined and we get no barbs
  809. if 'linewidth' not in kw and 'lw' not in kw:
  810. kw['linewidth'] = 1
  811. # Parse out the data arrays from the various configurations supported
  812. x, y, u, v, c = _parse_args(*args)
  813. self.x = x
  814. self.y = y
  815. xy = np.column_stack((x, y))
  816. # Make a collection
  817. barb_size = self._length ** 2 / 4 # Empirically determined
  818. mcollections.PolyCollection.__init__(self, [], (barb_size,),
  819. offsets=xy,
  820. transOffset=transform, **kw)
  821. self.set_transform(transforms.IdentityTransform())
  822. self.set_UVC(u, v, c)
  823. def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
  824. '''
  825. Find how many of each of the tail pieces is necessary. Flag
  826. specifies the increment for a flag, barb for a full barb, and half for
  827. half a barb. Mag should be the magnitude of a vector (i.e., >= 0).
  828. This returns a tuple of:
  829. (*number of flags*, *number of barbs*, *half_flag*, *empty_flag*)
  830. *half_flag* is a boolean whether half of a barb is needed,
  831. since there should only ever be one half on a given
  832. barb. *empty_flag* flag is an array of flags to easily tell if
  833. a barb is empty (too low to plot any barbs/flags.
  834. '''
  835. # If rounding, round to the nearest multiple of half, the smallest
  836. # increment
  837. if rounding:
  838. mag = half * (mag / half + 0.5).astype(int)
  839. num_flags = np.floor(mag / flag).astype(int)
  840. mag = np.mod(mag, flag)
  841. num_barb = np.floor(mag / full).astype(int)
  842. mag = np.mod(mag, full)
  843. half_flag = mag >= half
  844. empty_flag = ~(half_flag | (num_flags > 0) | (num_barb > 0))
  845. return num_flags, num_barb, half_flag, empty_flag
  846. def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
  847. pivot, sizes, fill_empty, flip):
  848. '''
  849. This function actually creates the wind barbs. *u* and *v*
  850. are components of the vector in the *x* and *y* directions,
  851. respectively.
  852. *nflags*, *nbarbs*, and *half_barb*, empty_flag* are,
  853. *respectively, the number of flags, number of barbs, flag for
  854. *half a barb, and flag for empty barb, ostensibly obtained
  855. *from :meth:`_find_tails`.
  856. *length* is the length of the barb staff in points.
  857. *pivot* specifies the point on the barb around which the
  858. entire barb should be rotated. Right now, valid options are
  859. 'tip' and 'middle'. Can also be a number, which shifts the start
  860. of the barb that many points from the origin.
  861. *sizes* is a dictionary of coefficients specifying the ratio
  862. of a given feature to the length of the barb. These features
  863. include:
  864. - *spacing*: space between features (flags, full/half
  865. barbs)
  866. - *height*: distance from shaft of top of a flag or full
  867. barb
  868. - *width* - width of a flag, twice the width of a full barb
  869. - *emptybarb* - radius of the circle used for low
  870. magnitudes
  871. *fill_empty* specifies whether the circle representing an
  872. empty barb should be filled or not (this changes the drawing
  873. of the polygon).
  874. *flip* is a flag indicating whether the features should be flipped to
  875. the other side of the barb (useful for winds in the southern
  876. hemisphere).
  877. This function returns list of arrays of vertices, defining a polygon
  878. for each of the wind barbs. These polygons have been rotated to
  879. properly align with the vector direction.
  880. '''
  881. # These control the spacing and size of barb elements relative to the
  882. # length of the shaft
  883. spacing = length * sizes.get('spacing', 0.125)
  884. full_height = length * sizes.get('height', 0.4)
  885. full_width = length * sizes.get('width', 0.25)
  886. empty_rad = length * sizes.get('emptybarb', 0.15)
  887. # Controls y point where to pivot the barb.
  888. pivot_points = dict(tip=0.0, middle=-length / 2.)
  889. # Check for flip
  890. if flip:
  891. full_height = -full_height
  892. endx = 0.0
  893. try:
  894. endy = float(pivot)
  895. except ValueError:
  896. endy = pivot_points[pivot.lower()]
  897. # Get the appropriate angle for the vector components. The offset is
  898. # due to the way the barb is initially drawn, going down the y-axis.
  899. # This makes sense in a meteorological mode of thinking since there 0
  900. # degrees corresponds to north (the y-axis traditionally)
  901. angles = -(ma.arctan2(v, u) + np.pi / 2)
  902. # Used for low magnitude. We just get the vertices, so if we make it
  903. # out here, it can be reused. The center set here should put the
  904. # center of the circle at the location(offset), rather than at the
  905. # same point as the barb pivot; this seems more sensible.
  906. circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
  907. if fill_empty:
  908. empty_barb = circ
  909. else:
  910. # If we don't want the empty one filled, we make a degenerate
  911. # polygon that wraps back over itself
  912. empty_barb = np.concatenate((circ, circ[::-1]))
  913. barb_list = []
  914. for index, angle in np.ndenumerate(angles):
  915. # If the vector magnitude is too weak to draw anything, plot an
  916. # empty circle instead
  917. if empty_flag[index]:
  918. # We can skip the transform since the circle has no preferred
  919. # orientation
  920. barb_list.append(empty_barb)
  921. continue
  922. poly_verts = [(endx, endy)]
  923. offset = length
  924. # Add vertices for each flag
  925. for i in range(nflags[index]):
  926. # The spacing that works for the barbs is a little to much for
  927. # the flags, but this only occurs when we have more than 1
  928. # flag.
  929. if offset != length:
  930. offset += spacing / 2.
  931. poly_verts.extend(
  932. [[endx, endy + offset],
  933. [endx + full_height, endy - full_width / 2 + offset],
  934. [endx, endy - full_width + offset]])
  935. offset -= full_width + spacing
  936. # Add vertices for each barb. These really are lines, but works
  937. # great adding 3 vertices that basically pull the polygon out and
  938. # back down the line
  939. for i in range(nbarbs[index]):
  940. poly_verts.extend(
  941. [(endx, endy + offset),
  942. (endx + full_height, endy + offset + full_width / 2),
  943. (endx, endy + offset)])
  944. offset -= spacing
  945. # Add the vertices for half a barb, if needed
  946. if half_barb[index]:
  947. # If the half barb is the first on the staff, traditionally it
  948. # is offset from the end to make it easy to distinguish from a
  949. # barb with a full one
  950. if offset == length:
  951. poly_verts.append((endx, endy + offset))
  952. offset -= 1.5 * spacing
  953. poly_verts.extend(
  954. [(endx, endy + offset),
  955. (endx + full_height / 2, endy + offset + full_width / 4),
  956. (endx, endy + offset)])
  957. # Rotate the barb according the angle. Making the barb first and
  958. # then rotating it made the math for drawing the barb really easy.
  959. # Also, the transform framework makes doing the rotation simple.
  960. poly_verts = transforms.Affine2D().rotate(-angle).transform(
  961. poly_verts)
  962. barb_list.append(poly_verts)
  963. return barb_list
  964. def set_UVC(self, U, V, C=None):
  965. self.u = ma.masked_invalid(U, copy=False).ravel()
  966. self.v = ma.masked_invalid(V, copy=False).ravel()
  967. if C is not None:
  968. c = ma.masked_invalid(C, copy=False).ravel()
  969. x, y, u, v, c = delete_masked_points(self.x.ravel(),
  970. self.y.ravel(),
  971. self.u, self.v, c)
  972. _check_consistent_shapes(x, y, u, v, c)
  973. else:
  974. x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(),
  975. self.u, self.v)
  976. _check_consistent_shapes(x, y, u, v)
  977. magnitude = np.hypot(u, v)
  978. flags, barbs, halves, empty = self._find_tails(magnitude,
  979. self.rounding,
  980. **self.barb_increments)
  981. # Get the vertices for each of the barbs
  982. plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
  983. self._length, self._pivot, self.sizes,
  984. self.fill_empty, self.flip)
  985. self.set_verts(plot_barbs)
  986. # Set the color array
  987. if C is not None:
  988. self.set_array(c)
  989. # Update the offsets in case the masked data changed
  990. xy = np.column_stack((x, y))
  991. self._offsets = xy
  992. self.stale = True
  993. def set_offsets(self, xy):
  994. """
  995. Set the offsets for the barb polygons. This saves the offsets passed
  996. in and actually sets version masked as appropriate for the existing
  997. U/V data. *offsets* should be a sequence.
  998. Parameters
  999. ----------
  1000. offsets : sequence of pairs of floats
  1001. """
  1002. self.x = xy[:, 0]
  1003. self.y = xy[:, 1]
  1004. x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(),
  1005. self.u, self.v)
  1006. _check_consistent_shapes(x, y, u, v)
  1007. xy = np.column_stack((x, y))
  1008. mcollections.PolyCollection.set_offsets(self, xy)
  1009. self.stale = True
  1010. set_offsets.__doc__ = mcollections.PolyCollection.set_offsets.__doc__
  1011. barbs_doc = _barbs_doc