_plotutils.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import numpy as np
  2. from scipy._lib.decorator import decorator as _decorator
  3. __all__ = ['delaunay_plot_2d', 'convex_hull_plot_2d', 'voronoi_plot_2d']
  4. @_decorator
  5. def _held_figure(func, obj, ax=None, **kw):
  6. import matplotlib.pyplot as plt
  7. if ax is None:
  8. fig = plt.figure()
  9. ax = fig.gca()
  10. return func(obj, ax=ax, **kw)
  11. # As of matplotlib 2.0, the "hold" mechanism is deprecated.
  12. # When matplotlib 1.x is no longer supported, this check can be removed.
  13. was_held = getattr(ax, 'ishold', lambda: True)()
  14. if was_held:
  15. return func(obj, ax=ax, **kw)
  16. try:
  17. ax.hold(True)
  18. return func(obj, ax=ax, **kw)
  19. finally:
  20. ax.hold(was_held)
  21. def _adjust_bounds(ax, points):
  22. margin = 0.1 * points.ptp(axis=0)
  23. xy_min = points.min(axis=0) - margin
  24. xy_max = points.max(axis=0) + margin
  25. ax.set_xlim(xy_min[0], xy_max[0])
  26. ax.set_ylim(xy_min[1], xy_max[1])
  27. @_held_figure
  28. def delaunay_plot_2d(tri, ax=None):
  29. """
  30. Plot the given Delaunay triangulation in 2-D
  31. Parameters
  32. ----------
  33. tri : scipy.spatial.Delaunay instance
  34. Triangulation to plot
  35. ax : matplotlib.axes.Axes instance, optional
  36. Axes to plot on
  37. Returns
  38. -------
  39. fig : matplotlib.figure.Figure instance
  40. Figure for the plot
  41. See Also
  42. --------
  43. Delaunay
  44. matplotlib.pyplot.triplot
  45. Notes
  46. -----
  47. Requires Matplotlib.
  48. Examples
  49. --------
  50. >>> import numpy as np
  51. >>> import matplotlib.pyplot as plt
  52. >>> from scipy.spatial import Delaunay, delaunay_plot_2d
  53. The Delaunay triangulation of a set of random points:
  54. >>> rng = np.random.default_rng()
  55. >>> points = rng.random((30, 2))
  56. >>> tri = Delaunay(points)
  57. Plot it:
  58. >>> _ = delaunay_plot_2d(tri)
  59. >>> plt.show()
  60. """
  61. if tri.points.shape[1] != 2:
  62. raise ValueError("Delaunay triangulation is not 2-D")
  63. x, y = tri.points.T
  64. ax.plot(x, y, 'o')
  65. ax.triplot(x, y, tri.simplices.copy())
  66. _adjust_bounds(ax, tri.points)
  67. return ax.figure
  68. @_held_figure
  69. def convex_hull_plot_2d(hull, ax=None):
  70. """
  71. Plot the given convex hull diagram in 2-D
  72. Parameters
  73. ----------
  74. hull : scipy.spatial.ConvexHull instance
  75. Convex hull to plot
  76. ax : matplotlib.axes.Axes instance, optional
  77. Axes to plot on
  78. Returns
  79. -------
  80. fig : matplotlib.figure.Figure instance
  81. Figure for the plot
  82. See Also
  83. --------
  84. ConvexHull
  85. Notes
  86. -----
  87. Requires Matplotlib.
  88. Examples
  89. --------
  90. >>> import numpy as np
  91. >>> import matplotlib.pyplot as plt
  92. >>> from scipy.spatial import ConvexHull, convex_hull_plot_2d
  93. The convex hull of a random set of points:
  94. >>> rng = np.random.default_rng()
  95. >>> points = rng.random((30, 2))
  96. >>> hull = ConvexHull(points)
  97. Plot it:
  98. >>> _ = convex_hull_plot_2d(hull)
  99. >>> plt.show()
  100. """
  101. from matplotlib.collections import LineCollection
  102. if hull.points.shape[1] != 2:
  103. raise ValueError("Convex hull is not 2-D")
  104. ax.plot(hull.points[:, 0], hull.points[:, 1], 'o')
  105. line_segments = [hull.points[simplex] for simplex in hull.simplices]
  106. ax.add_collection(LineCollection(line_segments,
  107. colors='k',
  108. linestyle='solid'))
  109. _adjust_bounds(ax, hull.points)
  110. return ax.figure
  111. @_held_figure
  112. def voronoi_plot_2d(vor, ax=None, **kw):
  113. """
  114. Plot the given Voronoi diagram in 2-D
  115. Parameters
  116. ----------
  117. vor : scipy.spatial.Voronoi instance
  118. Diagram to plot
  119. ax : matplotlib.axes.Axes instance, optional
  120. Axes to plot on
  121. show_points : bool, optional
  122. Add the Voronoi points to the plot.
  123. show_vertices : bool, optional
  124. Add the Voronoi vertices to the plot.
  125. line_colors : string, optional
  126. Specifies the line color for polygon boundaries
  127. line_width : float, optional
  128. Specifies the line width for polygon boundaries
  129. line_alpha : float, optional
  130. Specifies the line alpha for polygon boundaries
  131. point_size : float, optional
  132. Specifies the size of points
  133. Returns
  134. -------
  135. fig : matplotlib.figure.Figure instance
  136. Figure for the plot
  137. See Also
  138. --------
  139. Voronoi
  140. Notes
  141. -----
  142. Requires Matplotlib.
  143. Examples
  144. --------
  145. >>> import numpy as np
  146. >>> import matplotlib.pyplot as plt
  147. >>> from scipy.spatial import Voronoi, voronoi_plot_2d
  148. Create a set of points for the example:
  149. >>> rng = np.random.default_rng()
  150. >>> points = rng.random((10,2))
  151. Generate the Voronoi diagram for the points:
  152. >>> vor = Voronoi(points)
  153. Use `voronoi_plot_2d` to plot the diagram:
  154. >>> fig = voronoi_plot_2d(vor)
  155. Use `voronoi_plot_2d` to plot the diagram again, with some settings
  156. customized:
  157. >>> fig = voronoi_plot_2d(vor, show_vertices=False, line_colors='orange',
  158. ... line_width=2, line_alpha=0.6, point_size=2)
  159. >>> plt.show()
  160. """
  161. from matplotlib.collections import LineCollection
  162. if vor.points.shape[1] != 2:
  163. raise ValueError("Voronoi diagram is not 2-D")
  164. if kw.get('show_points', True):
  165. point_size = kw.get('point_size', None)
  166. ax.plot(vor.points[:, 0], vor.points[:, 1], '.', markersize=point_size)
  167. if kw.get('show_vertices', True):
  168. ax.plot(vor.vertices[:, 0], vor.vertices[:, 1], 'o')
  169. line_colors = kw.get('line_colors', 'k')
  170. line_width = kw.get('line_width', 1.0)
  171. line_alpha = kw.get('line_alpha', 1.0)
  172. center = vor.points.mean(axis=0)
  173. ptp_bound = vor.points.ptp(axis=0)
  174. finite_segments = []
  175. infinite_segments = []
  176. for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
  177. simplex = np.asarray(simplex)
  178. if np.all(simplex >= 0):
  179. finite_segments.append(vor.vertices[simplex])
  180. else:
  181. i = simplex[simplex >= 0][0] # finite end Voronoi vertex
  182. t = vor.points[pointidx[1]] - vor.points[pointidx[0]] # tangent
  183. t /= np.linalg.norm(t)
  184. n = np.array([-t[1], t[0]]) # normal
  185. midpoint = vor.points[pointidx].mean(axis=0)
  186. direction = np.sign(np.dot(midpoint - center, n)) * n
  187. if (vor.furthest_site):
  188. direction = -direction
  189. far_point = vor.vertices[i] + direction * ptp_bound.max()
  190. infinite_segments.append([vor.vertices[i], far_point])
  191. ax.add_collection(LineCollection(finite_segments,
  192. colors=line_colors,
  193. lw=line_width,
  194. alpha=line_alpha,
  195. linestyle='solid'))
  196. ax.add_collection(LineCollection(infinite_segments,
  197. colors=line_colors,
  198. lw=line_width,
  199. alpha=line_alpha,
  200. linestyle='dashed'))
  201. _adjust_bounds(ax, vor.points)
  202. return ax.figure