sankey.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. """
  2. Module for creating Sankey diagrams using Matplotlib.
  3. """
  4. import logging
  5. from types import SimpleNamespace
  6. import numpy as np
  7. from matplotlib.path import Path
  8. from matplotlib.patches import PathPatch
  9. from matplotlib.transforms import Affine2D
  10. from matplotlib import docstring
  11. from matplotlib import rcParams
  12. _log = logging.getLogger(__name__)
  13. __author__ = "Kevin L. Davies"
  14. __credits__ = ["Yannick Copin"]
  15. __license__ = "BSD"
  16. __version__ = "2011/09/16"
  17. # Angles [deg/90]
  18. RIGHT = 0
  19. UP = 1
  20. # LEFT = 2
  21. DOWN = 3
  22. class Sankey:
  23. """
  24. Sankey diagram.
  25. Sankey diagrams are a specific type of flow diagram, in which
  26. the width of the arrows is shown proportionally to the flow
  27. quantity. They are typically used to visualize energy or
  28. material or cost transfers between processes.
  29. `Wikipedia (6/1/2011) <https://en.wikipedia.org/wiki/Sankey_diagram>`_
  30. """
  31. def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
  32. radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
  33. margin=0.4, tolerance=1e-6, **kwargs):
  34. """
  35. Create a new Sankey instance.
  36. Optional keyword arguments:
  37. =============== ===================================================
  38. Field Description
  39. =============== ===================================================
  40. *ax* axes onto which the data should be plotted
  41. If *ax* isn't provided, new axes will be created.
  42. *scale* scaling factor for the flows
  43. *scale* sizes the width of the paths in order to
  44. maintain proper layout. The same scale is applied
  45. to all subdiagrams. The value should be chosen
  46. such that the product of the scale and the sum of
  47. the inputs is approximately 1.0 (and the product of
  48. the scale and the sum of the outputs is
  49. approximately -1.0).
  50. *unit* string representing the physical unit associated
  51. with the flow quantities
  52. If *unit* is None, then none of the quantities are
  53. labeled.
  54. *format* a Python number formatting string to be used in
  55. labeling the flow as a quantity (i.e., a number
  56. times a unit, where the unit is given)
  57. *gap* space between paths that break in/break away
  58. to/from the top or bottom
  59. *radius* inner radius of the vertical paths
  60. *shoulder* size of the shoulders of output arrowS
  61. *offset* text offset (from the dip or tip of the arrow)
  62. *head_angle* angle of the arrow heads (and negative of the angle
  63. of the tails) [deg]
  64. *margin* minimum space between Sankey outlines and the edge
  65. of the plot area
  66. *tolerance* acceptable maximum of the magnitude of the sum of
  67. flows
  68. The magnitude of the sum of connected flows cannot
  69. be greater than *tolerance*.
  70. =============== ===================================================
  71. The optional arguments listed above are applied to all subdiagrams so
  72. that there is consistent alignment and formatting.
  73. If :class:`Sankey` is instantiated with any keyword arguments other
  74. than those explicitly listed above (``**kwargs``), they will be passed
  75. to :meth:`add`, which will create the first subdiagram.
  76. In order to draw a complex Sankey diagram, create an instance of
  77. :class:`Sankey` by calling it without any kwargs::
  78. sankey = Sankey()
  79. Then add simple Sankey sub-diagrams::
  80. sankey.add() # 1
  81. sankey.add() # 2
  82. #...
  83. sankey.add() # n
  84. Finally, create the full diagram::
  85. sankey.finish()
  86. Or, instead, simply daisy-chain those calls::
  87. Sankey().add().add... .add().finish()
  88. See Also
  89. --------
  90. Sankey.add
  91. Sankey.finish
  92. Examples
  93. --------
  94. .. plot:: gallery/specialty_plots/sankey_basics.py
  95. """
  96. # Check the arguments.
  97. if gap < 0:
  98. raise ValueError(
  99. "'gap' is negative, which is not allowed because it would "
  100. "cause the paths to overlap")
  101. if radius > gap:
  102. raise ValueError(
  103. "'radius' is greater than 'gap', which is not allowed because "
  104. "it would cause the paths to overlap")
  105. if head_angle < 0:
  106. raise ValueError(
  107. "'head_angle' is negative, which is not allowed because it "
  108. "would cause inputs to look like outputs and vice versa")
  109. if tolerance < 0:
  110. raise ValueError(
  111. "'tolerance' is negative, but it must be a magnitude")
  112. # Create axes if necessary.
  113. if ax is None:
  114. import matplotlib.pyplot as plt
  115. fig = plt.figure()
  116. ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
  117. self.diagrams = []
  118. # Store the inputs.
  119. self.ax = ax
  120. self.unit = unit
  121. self.format = format
  122. self.scale = scale
  123. self.gap = gap
  124. self.radius = radius
  125. self.shoulder = shoulder
  126. self.offset = offset
  127. self.margin = margin
  128. self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
  129. self.tolerance = tolerance
  130. # Initialize the vertices of tight box around the diagram(s).
  131. self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))
  132. # If there are any kwargs, create the first subdiagram.
  133. if len(kwargs):
  134. self.add(**kwargs)
  135. def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)):
  136. """
  137. Return the codes and vertices for a rotated, scaled, and translated
  138. 90 degree arc.
  139. Optional keyword arguments:
  140. =============== ==========================================
  141. Keyword Description
  142. =============== ==========================================
  143. *quadrant* uses 0-based indexing (0, 1, 2, or 3)
  144. *cw* if True, clockwise
  145. *center* (x, y) tuple of the arc's center
  146. =============== ==========================================
  147. """
  148. # Note: It would be possible to use matplotlib's transforms to rotate,
  149. # scale, and translate the arc, but since the angles are discrete,
  150. # it's just as easy and maybe more efficient to do it here.
  151. ARC_CODES = [Path.LINETO,
  152. Path.CURVE4,
  153. Path.CURVE4,
  154. Path.CURVE4,
  155. Path.CURVE4,
  156. Path.CURVE4,
  157. Path.CURVE4]
  158. # Vertices of a cubic Bezier curve approximating a 90 deg arc
  159. # These can be determined by Path.arc(0, 90).
  160. ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00],
  161. [1.00000000e+00, 2.65114773e-01],
  162. [8.94571235e-01, 5.19642327e-01],
  163. [7.07106781e-01, 7.07106781e-01],
  164. [5.19642327e-01, 8.94571235e-01],
  165. [2.65114773e-01, 1.00000000e+00],
  166. # Insignificant
  167. # [6.12303177e-17, 1.00000000e+00]])
  168. [0.00000000e+00, 1.00000000e+00]])
  169. if quadrant == 0 or quadrant == 2:
  170. if cw:
  171. vertices = ARC_VERTICES
  172. else:
  173. vertices = ARC_VERTICES[:, ::-1] # Swap x and y.
  174. elif quadrant == 1 or quadrant == 3:
  175. # Negate x.
  176. if cw:
  177. # Swap x and y.
  178. vertices = np.column_stack((-ARC_VERTICES[:, 1],
  179. ARC_VERTICES[:, 0]))
  180. else:
  181. vertices = np.column_stack((-ARC_VERTICES[:, 0],
  182. ARC_VERTICES[:, 1]))
  183. if quadrant > 1:
  184. radius = -radius # Rotate 180 deg.
  185. return list(zip(ARC_CODES, radius * vertices +
  186. np.tile(center, (ARC_VERTICES.shape[0], 1))))
  187. def _add_input(self, path, angle, flow, length):
  188. """
  189. Add an input to a path and return its tip and label locations.
  190. """
  191. if angle is None:
  192. return [0, 0], [0, 0]
  193. else:
  194. x, y = path[-1][1] # Use the last point as a reference.
  195. dipdepth = (flow / 2) * self.pitch
  196. if angle == RIGHT:
  197. x -= length
  198. dip = [x + dipdepth, y + flow / 2.0]
  199. path.extend([(Path.LINETO, [x, y]),
  200. (Path.LINETO, dip),
  201. (Path.LINETO, [x, y + flow]),
  202. (Path.LINETO, [x + self.gap, y + flow])])
  203. label_location = [dip[0] - self.offset, dip[1]]
  204. else: # Vertical
  205. x -= self.gap
  206. if angle == UP:
  207. sign = 1
  208. else:
  209. sign = -1
  210. dip = [x - flow / 2, y - sign * (length - dipdepth)]
  211. if angle == DOWN:
  212. quadrant = 2
  213. else:
  214. quadrant = 1
  215. # Inner arc isn't needed if inner radius is zero
  216. if self.radius:
  217. path.extend(self._arc(quadrant=quadrant,
  218. cw=angle == UP,
  219. radius=self.radius,
  220. center=(x + self.radius,
  221. y - sign * self.radius)))
  222. else:
  223. path.append((Path.LINETO, [x, y]))
  224. path.extend([(Path.LINETO, [x, y - sign * length]),
  225. (Path.LINETO, dip),
  226. (Path.LINETO, [x - flow, y - sign * length])])
  227. path.extend(self._arc(quadrant=quadrant,
  228. cw=angle == DOWN,
  229. radius=flow + self.radius,
  230. center=(x + self.radius,
  231. y - sign * self.radius)))
  232. path.append((Path.LINETO, [x - flow, y + sign * flow]))
  233. label_location = [dip[0], dip[1] - sign * self.offset]
  234. return dip, label_location
  235. def _add_output(self, path, angle, flow, length):
  236. """
  237. Append an output to a path and return its tip and label locations.
  238. .. note:: *flow* is negative for an output.
  239. """
  240. if angle is None:
  241. return [0, 0], [0, 0]
  242. else:
  243. x, y = path[-1][1] # Use the last point as a reference.
  244. tipheight = (self.shoulder - flow / 2) * self.pitch
  245. if angle == RIGHT:
  246. x += length
  247. tip = [x + tipheight, y + flow / 2.0]
  248. path.extend([(Path.LINETO, [x, y]),
  249. (Path.LINETO, [x, y + self.shoulder]),
  250. (Path.LINETO, tip),
  251. (Path.LINETO, [x, y - self.shoulder + flow]),
  252. (Path.LINETO, [x, y + flow]),
  253. (Path.LINETO, [x - self.gap, y + flow])])
  254. label_location = [tip[0] + self.offset, tip[1]]
  255. else: # Vertical
  256. x += self.gap
  257. if angle == UP:
  258. sign = 1
  259. else:
  260. sign = -1
  261. tip = [x - flow / 2.0, y + sign * (length + tipheight)]
  262. if angle == UP:
  263. quadrant = 3
  264. else:
  265. quadrant = 0
  266. # Inner arc isn't needed if inner radius is zero
  267. if self.radius:
  268. path.extend(self._arc(quadrant=quadrant,
  269. cw=angle == UP,
  270. radius=self.radius,
  271. center=(x - self.radius,
  272. y + sign * self.radius)))
  273. else:
  274. path.append((Path.LINETO, [x, y]))
  275. path.extend([(Path.LINETO, [x, y + sign * length]),
  276. (Path.LINETO, [x - self.shoulder,
  277. y + sign * length]),
  278. (Path.LINETO, tip),
  279. (Path.LINETO, [x + self.shoulder - flow,
  280. y + sign * length]),
  281. (Path.LINETO, [x - flow, y + sign * length])])
  282. path.extend(self._arc(quadrant=quadrant,
  283. cw=angle == DOWN,
  284. radius=self.radius - flow,
  285. center=(x - self.radius,
  286. y + sign * self.radius)))
  287. path.append((Path.LINETO, [x - flow, y + sign * flow]))
  288. label_location = [tip[0], tip[1] + sign * self.offset]
  289. return tip, label_location
  290. def _revert(self, path, first_action=Path.LINETO):
  291. """
  292. A path is not simply reversible by path[::-1] since the code
  293. specifies an action to take from the **previous** point.
  294. """
  295. reverse_path = []
  296. next_code = first_action
  297. for code, position in path[::-1]:
  298. reverse_path.append((next_code, position))
  299. next_code = code
  300. return reverse_path
  301. # This might be more efficient, but it fails because 'tuple' object
  302. # doesn't support item assignment:
  303. # path[1] = path[1][-1:0:-1]
  304. # path[1][0] = first_action
  305. # path[2] = path[2][::-1]
  306. # return path
  307. @docstring.dedent_interpd
  308. def add(self, patchlabel='', flows=None, orientations=None, labels='',
  309. trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0),
  310. rotation=0, **kwargs):
  311. """
  312. Add a simple Sankey diagram with flows at the same hierarchical level.
  313. Parameters
  314. ----------
  315. patchlabel : str
  316. Label to be placed at the center of the diagram.
  317. Note that *label* (not *patchlabel*) can be passed as keyword
  318. argument to create an entry in the legend.
  319. flows : list of float
  320. Array of flow values. By convention, inputs are positive and
  321. outputs are negative.
  322. Flows are placed along the top of the diagram from the inside out
  323. in order of their index within *flows*. They are placed along the
  324. sides of the diagram from the top down and along the bottom from
  325. the outside in.
  326. If the sum of the inputs and outputs is
  327. nonzero, the discrepancy will appear as a cubic Bezier curve along
  328. the top and bottom edges of the trunk.
  329. orientations : list of {-1, 0, 1}
  330. List of orientations of the flows (or a single orientation to be
  331. used for all flows). Valid values are 0 (inputs from
  332. the left, outputs to the right), 1 (from and to the top) or -1
  333. (from and to the bottom).
  334. labels : list of (str or None)
  335. List of labels for the flows (or a single label to be used for all
  336. flows). Each label may be *None* (no label), or a labeling string.
  337. If an entry is a (possibly empty) string, then the quantity for the
  338. corresponding flow will be shown below the string. However, if
  339. the *unit* of the main diagram is None, then quantities are never
  340. shown, regardless of the value of this argument.
  341. trunklength : float
  342. Length between the bases of the input and output groups (in
  343. data-space units).
  344. pathlengths : list of float
  345. List of lengths of the vertical arrows before break-in or after
  346. break-away. If a single value is given, then it will be applied to
  347. the first (inside) paths on the top and bottom, and the length of
  348. all other arrows will be justified accordingly. The *pathlengths*
  349. are not applied to the horizontal inputs and outputs.
  350. prior : int
  351. Index of the prior diagram to which this diagram should be
  352. connected.
  353. connect : (int, int)
  354. A (prior, this) tuple indexing the flow of the prior diagram and
  355. the flow of this diagram which should be connected. If this is the
  356. first diagram or *prior* is *None*, *connect* will be ignored.
  357. rotation : float
  358. Angle of rotation of the diagram in degrees. The interpretation of
  359. the *orientations* argument will be rotated accordingly (e.g., if
  360. *rotation* == 90, an *orientations* entry of 1 means to/from the
  361. left). *rotation* is ignored if this diagram is connected to an
  362. existing one (using *prior* and *connect*).
  363. Returns
  364. -------
  365. Sankey
  366. The current `.Sankey` instance.
  367. Other Parameters
  368. ----------------
  369. **kwargs
  370. Additional keyword arguments set `matplotlib.patches.PathPatch`
  371. properties, listed below. For example, one may want to use
  372. ``fill=False`` or ``label="A legend entry"``.
  373. %(Patch)s
  374. See Also
  375. --------
  376. Sankey.finish
  377. """
  378. # Check and preprocess the arguments.
  379. if flows is None:
  380. flows = np.array([1.0, -1.0])
  381. else:
  382. flows = np.array(flows)
  383. n = flows.shape[0] # Number of flows
  384. if rotation is None:
  385. rotation = 0
  386. else:
  387. # In the code below, angles are expressed in deg/90.
  388. rotation /= 90.0
  389. if orientations is None:
  390. orientations = 0
  391. try:
  392. orientations = np.broadcast_to(orientations, n)
  393. except ValueError:
  394. raise ValueError(
  395. f"The shapes of 'flows' {np.shape(flows)} and 'orientations' "
  396. f"{np.shape(orientations)} are incompatible"
  397. ) from None
  398. try:
  399. labels = np.broadcast_to(labels, n)
  400. except ValueError:
  401. raise ValueError(
  402. f"The shapes of 'flows' {np.shape(flows)} and 'labels' "
  403. f"{np.shape(labels)} are incompatible"
  404. ) from None
  405. if trunklength < 0:
  406. raise ValueError(
  407. "'trunklength' is negative, which is not allowed because it "
  408. "would cause poor layout")
  409. if np.abs(np.sum(flows)) > self.tolerance:
  410. _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); "
  411. "is the system not at steady state?",
  412. np.sum(flows), patchlabel)
  413. scaled_flows = self.scale * flows
  414. gain = sum(max(flow, 0) for flow in scaled_flows)
  415. loss = sum(min(flow, 0) for flow in scaled_flows)
  416. if prior is not None:
  417. if prior < 0:
  418. raise ValueError("The index of the prior diagram is negative")
  419. if min(connect) < 0:
  420. raise ValueError(
  421. "At least one of the connection indices is negative")
  422. if prior >= len(self.diagrams):
  423. raise ValueError(
  424. f"The index of the prior diagram is {prior}, but there "
  425. f"are only {len(self.diagrams)} other diagrams")
  426. if connect[0] >= len(self.diagrams[prior].flows):
  427. raise ValueError(
  428. "The connection index to the source diagram is {}, but "
  429. "that diagram has only {} flows".format(
  430. connect[0], len(self.diagrams[prior].flows)))
  431. if connect[1] >= n:
  432. raise ValueError(
  433. f"The connection index to this diagram is {connect[1]}, "
  434. f"but this diagram has only {n} flows")
  435. if self.diagrams[prior].angles[connect[0]] is None:
  436. raise ValueError(
  437. f"The connection cannot be made, which may occur if the "
  438. f"magnitude of flow {connect[0]} of diagram {prior} is "
  439. f"less than the specified tolerance")
  440. flow_error = (self.diagrams[prior].flows[connect[0]] +
  441. flows[connect[1]])
  442. if abs(flow_error) >= self.tolerance:
  443. raise ValueError(
  444. f"The scaled sum of the connected flows is {flow_error}, "
  445. f"which is not within the tolerance ({self.tolerance})")
  446. # Determine if the flows are inputs.
  447. are_inputs = [None] * n
  448. for i, flow in enumerate(flows):
  449. if flow >= self.tolerance:
  450. are_inputs[i] = True
  451. elif flow <= -self.tolerance:
  452. are_inputs[i] = False
  453. else:
  454. _log.info(
  455. "The magnitude of flow %d (%f) is below the tolerance "
  456. "(%f).\nIt will not be shown, and it cannot be used in a "
  457. "connection.", i, flow, self.tolerance)
  458. # Determine the angles of the arrows (before rotation).
  459. angles = [None] * n
  460. for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)):
  461. if orient == 1:
  462. if is_input:
  463. angles[i] = DOWN
  464. elif not is_input:
  465. # Be specific since is_input can be None.
  466. angles[i] = UP
  467. elif orient == 0:
  468. if is_input is not None:
  469. angles[i] = RIGHT
  470. else:
  471. if orient != -1:
  472. raise ValueError(
  473. f"The value of orientations[{i}] is {orient}, "
  474. f"but it must be -1, 0, or 1")
  475. if is_input:
  476. angles[i] = UP
  477. elif not is_input:
  478. angles[i] = DOWN
  479. # Justify the lengths of the paths.
  480. if np.iterable(pathlengths):
  481. if len(pathlengths) != n:
  482. raise ValueError(
  483. f"The lengths of 'flows' ({n}) and 'pathlengths' "
  484. f"({len(pathlengths)}) are incompatible")
  485. else: # Make pathlengths into a list.
  486. urlength = pathlengths
  487. ullength = pathlengths
  488. lrlength = pathlengths
  489. lllength = pathlengths
  490. d = dict(RIGHT=pathlengths)
  491. pathlengths = [d.get(angle, 0) for angle in angles]
  492. # Determine the lengths of the top-side arrows
  493. # from the middle outwards.
  494. for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs,
  495. scaled_flows)):
  496. if angle == DOWN and is_input:
  497. pathlengths[i] = ullength
  498. ullength += flow
  499. elif angle == UP and not is_input:
  500. pathlengths[i] = urlength
  501. urlength -= flow # Flow is negative for outputs.
  502. # Determine the lengths of the bottom-side arrows
  503. # from the middle outwards.
  504. for i, (angle, is_input, flow) in enumerate(reversed(list(zip(
  505. angles, are_inputs, scaled_flows)))):
  506. if angle == UP and is_input:
  507. pathlengths[n - i - 1] = lllength
  508. lllength += flow
  509. elif angle == DOWN and not is_input:
  510. pathlengths[n - i - 1] = lrlength
  511. lrlength -= flow
  512. # Determine the lengths of the left-side arrows
  513. # from the bottom upwards.
  514. has_left_input = False
  515. for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
  516. angles, are_inputs, zip(scaled_flows, pathlengths))))):
  517. if angle == RIGHT:
  518. if is_input:
  519. if has_left_input:
  520. pathlengths[n - i - 1] = 0
  521. else:
  522. has_left_input = True
  523. # Determine the lengths of the right-side arrows
  524. # from the top downwards.
  525. has_right_output = False
  526. for i, (angle, is_input, spec) in enumerate(zip(
  527. angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
  528. if angle == RIGHT:
  529. if not is_input:
  530. if has_right_output:
  531. pathlengths[i] = 0
  532. else:
  533. has_right_output = True
  534. # Begin the subpaths, and smooth the transition if the sum of the flows
  535. # is nonzero.
  536. urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right
  537. gain / 2.0]),
  538. (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
  539. gain / 2.0]),
  540. (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
  541. gain / 2.0]),
  542. (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
  543. -loss / 2.0]),
  544. (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
  545. -loss / 2.0]),
  546. (Path.LINETO, [(trunklength / 2.0 - self.gap),
  547. -loss / 2.0])]
  548. llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left
  549. loss / 2.0]),
  550. (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
  551. loss / 2.0]),
  552. (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
  553. loss / 2.0]),
  554. (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
  555. -gain / 2.0]),
  556. (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
  557. -gain / 2.0]),
  558. (Path.LINETO, [(self.gap - trunklength / 2.0),
  559. -gain / 2.0])]
  560. lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right
  561. loss / 2.0])]
  562. ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left
  563. gain / 2.0])]
  564. # Add the subpaths and assign the locations of the tips and labels.
  565. tips = np.zeros((n, 2))
  566. label_locations = np.zeros((n, 2))
  567. # Add the top-side inputs and outputs from the middle outwards.
  568. for i, (angle, is_input, spec) in enumerate(zip(
  569. angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
  570. if angle == DOWN and is_input:
  571. tips[i, :], label_locations[i, :] = self._add_input(
  572. ulpath, angle, *spec)
  573. elif angle == UP and not is_input:
  574. tips[i, :], label_locations[i, :] = self._add_output(
  575. urpath, angle, *spec)
  576. # Add the bottom-side inputs and outputs from the middle outwards.
  577. for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
  578. angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
  579. if angle == UP and is_input:
  580. tip, label_location = self._add_input(llpath, angle, *spec)
  581. tips[n - i - 1, :] = tip
  582. label_locations[n - i - 1, :] = label_location
  583. elif angle == DOWN and not is_input:
  584. tip, label_location = self._add_output(lrpath, angle, *spec)
  585. tips[n - i - 1, :] = tip
  586. label_locations[n - i - 1, :] = label_location
  587. # Add the left-side inputs from the bottom upwards.
  588. has_left_input = False
  589. for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
  590. angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
  591. if angle == RIGHT and is_input:
  592. if not has_left_input:
  593. # Make sure the lower path extends
  594. # at least as far as the upper one.
  595. if llpath[-1][1][0] > ulpath[-1][1][0]:
  596. llpath.append((Path.LINETO, [ulpath[-1][1][0],
  597. llpath[-1][1][1]]))
  598. has_left_input = True
  599. tip, label_location = self._add_input(llpath, angle, *spec)
  600. tips[n - i - 1, :] = tip
  601. label_locations[n - i - 1, :] = label_location
  602. # Add the right-side outputs from the top downwards.
  603. has_right_output = False
  604. for i, (angle, is_input, spec) in enumerate(zip(
  605. angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
  606. if angle == RIGHT and not is_input:
  607. if not has_right_output:
  608. # Make sure the upper path extends
  609. # at least as far as the lower one.
  610. if urpath[-1][1][0] < lrpath[-1][1][0]:
  611. urpath.append((Path.LINETO, [lrpath[-1][1][0],
  612. urpath[-1][1][1]]))
  613. has_right_output = True
  614. tips[i, :], label_locations[i, :] = self._add_output(
  615. urpath, angle, *spec)
  616. # Trim any hanging vertices.
  617. if not has_left_input:
  618. ulpath.pop()
  619. llpath.pop()
  620. if not has_right_output:
  621. lrpath.pop()
  622. urpath.pop()
  623. # Concatenate the subpaths in the correct order (clockwise from top).
  624. path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) +
  625. [(Path.CLOSEPOLY, urpath[0][1])])
  626. # Create a patch with the Sankey outline.
  627. codes, vertices = zip(*path)
  628. vertices = np.array(vertices)
  629. def _get_angle(a, r):
  630. if a is None:
  631. return None
  632. else:
  633. return a + r
  634. if prior is None:
  635. if rotation != 0: # By default, none of this is needed.
  636. angles = [_get_angle(angle, rotation) for angle in angles]
  637. rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
  638. tips = rotate(tips)
  639. label_locations = rotate(label_locations)
  640. vertices = rotate(vertices)
  641. text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center')
  642. else:
  643. rotation = (self.diagrams[prior].angles[connect[0]] -
  644. angles[connect[1]])
  645. angles = [_get_angle(angle, rotation) for angle in angles]
  646. rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
  647. tips = rotate(tips)
  648. offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]]
  649. translate = Affine2D().translate(*offset).transform_affine
  650. tips = translate(tips)
  651. label_locations = translate(rotate(label_locations))
  652. vertices = translate(rotate(vertices))
  653. kwds = dict(s=patchlabel, ha='center', va='center')
  654. text = self.ax.text(*offset, **kwds)
  655. if rcParams['_internal.classic_mode']:
  656. fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4'))
  657. lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5))
  658. else:
  659. fc = kwargs.pop('fc', kwargs.pop('facecolor', None))
  660. lw = kwargs.pop('lw', kwargs.pop('linewidth', None))
  661. if fc is None:
  662. fc = next(self.ax._get_patches_for_fill.prop_cycler)['color']
  663. patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)
  664. self.ax.add_patch(patch)
  665. # Add the path labels.
  666. texts = []
  667. for number, angle, label, location in zip(flows, angles, labels,
  668. label_locations):
  669. if label is None or angle is None:
  670. label = ''
  671. elif self.unit is not None:
  672. quantity = self.format % abs(number) + self.unit
  673. if label != '':
  674. label += "\n"
  675. label += quantity
  676. texts.append(self.ax.text(x=location[0], y=location[1],
  677. s=label,
  678. ha='center', va='center'))
  679. # Text objects are placed even they are empty (as long as the magnitude
  680. # of the corresponding flow is larger than the tolerance) in case the
  681. # user wants to provide labels later.
  682. # Expand the size of the diagram if necessary.
  683. self.extent = (min(np.min(vertices[:, 0]),
  684. np.min(label_locations[:, 0]),
  685. self.extent[0]),
  686. max(np.max(vertices[:, 0]),
  687. np.max(label_locations[:, 0]),
  688. self.extent[1]),
  689. min(np.min(vertices[:, 1]),
  690. np.min(label_locations[:, 1]),
  691. self.extent[2]),
  692. max(np.max(vertices[:, 1]),
  693. np.max(label_locations[:, 1]),
  694. self.extent[3]))
  695. # Include both vertices _and_ label locations in the extents; there are
  696. # where either could determine the margins (e.g., arrow shoulders).
  697. # Add this diagram as a subdiagram.
  698. self.diagrams.append(
  699. SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
  700. text=text, texts=texts))
  701. # Allow a daisy-chained call structure (see docstring for the class).
  702. return self
  703. def finish(self):
  704. """
  705. Adjust the axes and return a list of information about the Sankey
  706. subdiagram(s).
  707. Return value is a list of subdiagrams represented with the following
  708. fields:
  709. =============== ===================================================
  710. Field Description
  711. =============== ===================================================
  712. *patch* Sankey outline (an instance of
  713. :class:`~matplotlib.patches.PathPatch`)
  714. *flows* values of the flows (positive for input, negative
  715. for output)
  716. *angles* list of angles of the arrows [deg/90]
  717. For example, if the diagram has not been rotated,
  718. an input to the top side will have an angle of 3
  719. (DOWN), and an output from the top side will have
  720. an angle of 1 (UP). If a flow has been skipped
  721. (because its magnitude is less than *tolerance*),
  722. then its angle will be *None*.
  723. *tips* array in which each row is an [x, y] pair
  724. indicating the positions of the tips (or "dips") of
  725. the flow paths
  726. If the magnitude of a flow is less the *tolerance*
  727. for the instance of :class:`Sankey`, the flow is
  728. skipped and its tip will be at the center of the
  729. diagram.
  730. *text* :class:`~matplotlib.text.Text` instance for the
  731. label of the diagram
  732. *texts* list of :class:`~matplotlib.text.Text` instances
  733. for the labels of flows
  734. =============== ===================================================
  735. See Also
  736. --------
  737. Sankey.add
  738. """
  739. self.ax.axis([self.extent[0] - self.margin,
  740. self.extent[1] + self.margin,
  741. self.extent[2] - self.margin,
  742. self.extent[3] + self.margin])
  743. self.ax.set_aspect('equal', adjustable='datalim')
  744. return self.diagrams