patheffects.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """
  2. Defines classes for path effects. The path effects are supported in `~.Text`,
  3. `~.Line2D` and `~.Patch`.
  4. .. seealso::
  5. :doc:`/tutorials/advanced/patheffects_guide`
  6. """
  7. from matplotlib.backend_bases import RendererBase
  8. from matplotlib import colors as mcolors
  9. from matplotlib import patches as mpatches
  10. from matplotlib import transforms as mtransforms
  11. class AbstractPathEffect:
  12. """
  13. A base class for path effects.
  14. Subclasses should override the ``draw_path`` method to add effect
  15. functionality.
  16. """
  17. def __init__(self, offset=(0., 0.)):
  18. """
  19. Parameters
  20. ----------
  21. offset : pair of floats
  22. The offset to apply to the path, measured in points.
  23. """
  24. self._offset = offset
  25. def _offset_transform(self, renderer):
  26. """Apply the offset to the given transform."""
  27. return mtransforms.Affine2D().translate(
  28. *map(renderer.points_to_pixels, self._offset))
  29. def _update_gc(self, gc, new_gc_dict):
  30. """
  31. Update the given GraphicsCollection with the given
  32. dictionary of properties. The keys in the dictionary are used to
  33. identify the appropriate set_ method on the gc.
  34. """
  35. new_gc_dict = new_gc_dict.copy()
  36. dashes = new_gc_dict.pop("dashes", None)
  37. if dashes:
  38. gc.set_dashes(**dashes)
  39. for k, v in new_gc_dict.items():
  40. set_method = getattr(gc, 'set_' + k, None)
  41. if not callable(set_method):
  42. raise AttributeError('Unknown property {0}'.format(k))
  43. set_method(v)
  44. return gc
  45. def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):
  46. """
  47. Derived should override this method. The arguments are the same
  48. as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
  49. except the first argument is a renderer.
  50. """
  51. # Get the real renderer, not a PathEffectRenderer.
  52. if isinstance(renderer, PathEffectRenderer):
  53. renderer = renderer._renderer
  54. return renderer.draw_path(gc, tpath, affine, rgbFace)
  55. class PathEffectRenderer(RendererBase):
  56. """
  57. Implements a Renderer which contains another renderer.
  58. This proxy then intercepts draw calls, calling the appropriate
  59. :class:`AbstractPathEffect` draw method.
  60. .. note::
  61. Not all methods have been overridden on this RendererBase subclass.
  62. It may be necessary to add further methods to extend the PathEffects
  63. capabilities further.
  64. """
  65. def __init__(self, path_effects, renderer):
  66. """
  67. Parameters
  68. ----------
  69. path_effects : iterable of :class:`AbstractPathEffect`
  70. The path effects which this renderer represents.
  71. renderer : `matplotlib.backend_bases.RendererBase` subclass
  72. """
  73. self._path_effects = path_effects
  74. self._renderer = renderer
  75. def copy_with_path_effect(self, path_effects):
  76. return self.__class__(path_effects, self._renderer)
  77. def draw_path(self, gc, tpath, affine, rgbFace=None):
  78. for path_effect in self._path_effects:
  79. path_effect.draw_path(self._renderer, gc, tpath, affine,
  80. rgbFace)
  81. def draw_markers(
  82. self, gc, marker_path, marker_trans, path, *args, **kwargs):
  83. # We do a little shimmy so that all markers are drawn for each path
  84. # effect in turn. Essentially, we induce recursion (depth 1) which is
  85. # terminated once we have just a single path effect to work with.
  86. if len(self._path_effects) == 1:
  87. # Call the base path effect function - this uses the unoptimised
  88. # approach of calling "draw_path" multiple times.
  89. return RendererBase.draw_markers(self, gc, marker_path,
  90. marker_trans, path, *args,
  91. **kwargs)
  92. for path_effect in self._path_effects:
  93. renderer = self.copy_with_path_effect([path_effect])
  94. # Recursively call this method, only next time we will only have
  95. # one path effect.
  96. renderer.draw_markers(gc, marker_path, marker_trans, path,
  97. *args, **kwargs)
  98. def draw_path_collection(self, gc, master_transform, paths, *args,
  99. **kwargs):
  100. # We do a little shimmy so that all paths are drawn for each path
  101. # effect in turn. Essentially, we induce recursion (depth 1) which is
  102. # terminated once we have just a single path effect to work with.
  103. if len(self._path_effects) == 1:
  104. # Call the base path effect function - this uses the unoptimised
  105. # approach of calling "draw_path" multiple times.
  106. return RendererBase.draw_path_collection(self, gc,
  107. master_transform, paths,
  108. *args, **kwargs)
  109. for path_effect in self._path_effects:
  110. renderer = self.copy_with_path_effect([path_effect])
  111. # Recursively call this method, only next time we will only have
  112. # one path effect.
  113. renderer.draw_path_collection(gc, master_transform, paths,
  114. *args, **kwargs)
  115. def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
  116. # Implements the naive text drawing as is found in RendererBase.
  117. path, transform = self._get_text_path_transform(x, y, s, prop,
  118. angle, ismath)
  119. color = gc.get_rgb()
  120. gc.set_linewidth(0.0)
  121. self.draw_path(gc, path, transform, rgbFace=color)
  122. def __getattribute__(self, name):
  123. if name in ['flipy', 'get_canvas_width_height', 'new_gc',
  124. 'points_to_pixels', '_text2path', 'height', 'width']:
  125. return getattr(self._renderer, name)
  126. else:
  127. return object.__getattribute__(self, name)
  128. class Normal(AbstractPathEffect):
  129. """
  130. The "identity" PathEffect.
  131. The Normal PathEffect's sole purpose is to draw the original artist with
  132. no special path effect.
  133. """
  134. def _subclass_with_normal(effect_class):
  135. """
  136. Create a PathEffect class combining *effect_class* and a normal draw.
  137. """
  138. class withEffect(effect_class):
  139. def draw_path(self, renderer, gc, tpath, affine, rgbFace):
  140. super().draw_path(renderer, gc, tpath, affine, rgbFace)
  141. renderer.draw_path(gc, tpath, affine, rgbFace)
  142. withEffect.__name__ = f"with{effect_class.__name__}"
  143. withEffect.__qualname__ = f"with{effect_class.__name__}"
  144. withEffect.__doc__ = f"""
  145. A shortcut PathEffect for applying `.{effect_class.__name__}` and then
  146. drawing the original Artist.
  147. With this class you can use ::
  148. artist.set_path_effects([path_effects.with{effect_class.__name__}()])
  149. as a shortcut for ::
  150. artist.set_path_effects([path_effects.{effect_class.__name__}(),
  151. path_effects.Normal()])
  152. """
  153. # Docstring inheritance doesn't work for locally-defined subclasses.
  154. withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__
  155. return withEffect
  156. class Stroke(AbstractPathEffect):
  157. """A line based PathEffect which re-draws a stroke."""
  158. def __init__(self, offset=(0, 0), **kwargs):
  159. """
  160. The path will be stroked with its gc updated with the given
  161. keyword arguments, i.e., the keyword arguments should be valid
  162. gc parameter values.
  163. """
  164. super().__init__(offset)
  165. self._gc = kwargs
  166. def draw_path(self, renderer, gc, tpath, affine, rgbFace):
  167. """Draw the path with updated gc."""
  168. gc0 = renderer.new_gc() # Don't modify gc, but a copy!
  169. gc0.copy_properties(gc)
  170. gc0 = self._update_gc(gc0, self._gc)
  171. renderer.draw_path(
  172. gc0, tpath, affine + self._offset_transform(renderer), rgbFace)
  173. gc0.restore()
  174. withStroke = _subclass_with_normal(effect_class=Stroke)
  175. class SimplePatchShadow(AbstractPathEffect):
  176. """A simple shadow via a filled patch."""
  177. def __init__(self, offset=(2, -2),
  178. shadow_rgbFace=None, alpha=None,
  179. rho=0.3, **kwargs):
  180. """
  181. Parameters
  182. ----------
  183. offset : pair of floats
  184. The offset of the shadow in points.
  185. shadow_rgbFace : color
  186. The shadow color.
  187. alpha : float, default: 0.3
  188. The alpha transparency of the created shadow patch.
  189. http://matplotlib.1069221.n5.nabble.com/path-effects-question-td27630.html
  190. rho : float, default: 0.3
  191. A scale factor to apply to the rgbFace color if `shadow_rgbFace`
  192. is not specified.
  193. **kwargs
  194. Extra keywords are stored and passed through to
  195. :meth:`AbstractPathEffect._update_gc`.
  196. """
  197. super().__init__(offset)
  198. if shadow_rgbFace is None:
  199. self._shadow_rgbFace = shadow_rgbFace
  200. else:
  201. self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
  202. if alpha is None:
  203. alpha = 0.3
  204. self._alpha = alpha
  205. self._rho = rho
  206. #: The dictionary of keywords to update the graphics collection with.
  207. self._gc = kwargs
  208. def draw_path(self, renderer, gc, tpath, affine, rgbFace):
  209. """
  210. Overrides the standard draw_path to add the shadow offset and
  211. necessary color changes for the shadow.
  212. """
  213. gc0 = renderer.new_gc() # Don't modify gc, but a copy!
  214. gc0.copy_properties(gc)
  215. if self._shadow_rgbFace is None:
  216. r, g, b = (rgbFace or (1., 1., 1.))[:3]
  217. # Scale the colors by a factor to improve the shadow effect.
  218. shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
  219. else:
  220. shadow_rgbFace = self._shadow_rgbFace
  221. gc0.set_foreground("none")
  222. gc0.set_alpha(self._alpha)
  223. gc0.set_linewidth(0)
  224. gc0 = self._update_gc(gc0, self._gc)
  225. renderer.draw_path(
  226. gc0, tpath, affine + self._offset_transform(renderer),
  227. shadow_rgbFace)
  228. gc0.restore()
  229. withSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow)
  230. class SimpleLineShadow(AbstractPathEffect):
  231. """A simple shadow via a line."""
  232. def __init__(self, offset=(2, -2),
  233. shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
  234. """
  235. Parameters
  236. ----------
  237. offset : pair of floats
  238. The offset to apply to the path, in points.
  239. shadow_color : color, default: 'black'
  240. The shadow color.
  241. A value of ``None`` takes the original artist's color
  242. with a scale factor of *rho*.
  243. alpha : float, default: 0.3
  244. The alpha transparency of the created shadow patch.
  245. rho : float, default: 0.3
  246. A scale factor to apply to the rgbFace color if `shadow_rgbFace`
  247. is ``None``.
  248. **kwargs
  249. Extra keywords are stored and passed through to
  250. :meth:`AbstractPathEffect._update_gc`.
  251. """
  252. super().__init__(offset)
  253. if shadow_color is None:
  254. self._shadow_color = shadow_color
  255. else:
  256. self._shadow_color = mcolors.to_rgba(shadow_color)
  257. self._alpha = alpha
  258. self._rho = rho
  259. #: The dictionary of keywords to update the graphics collection with.
  260. self._gc = kwargs
  261. def draw_path(self, renderer, gc, tpath, affine, rgbFace):
  262. """
  263. Overrides the standard draw_path to add the shadow offset and
  264. necessary color changes for the shadow.
  265. """
  266. gc0 = renderer.new_gc() # Don't modify gc, but a copy!
  267. gc0.copy_properties(gc)
  268. if self._shadow_color is None:
  269. r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3]
  270. # Scale the colors by a factor to improve the shadow effect.
  271. shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
  272. else:
  273. shadow_rgbFace = self._shadow_color
  274. gc0.set_foreground(shadow_rgbFace)
  275. gc0.set_alpha(self._alpha)
  276. gc0 = self._update_gc(gc0, self._gc)
  277. renderer.draw_path(
  278. gc0, tpath, affine + self._offset_transform(renderer))
  279. gc0.restore()
  280. class PathPatchEffect(AbstractPathEffect):
  281. """
  282. Draws a `.PathPatch` instance whose Path comes from the original
  283. PathEffect artist.
  284. """
  285. def __init__(self, offset=(0, 0), **kwargs):
  286. """
  287. Parameters
  288. ----------
  289. offset : pair of floats
  290. The offset to apply to the path, in points.
  291. **kwargs
  292. All keyword arguments are passed through to the
  293. :class:`~matplotlib.patches.PathPatch` constructor. The
  294. properties which cannot be overridden are "path", "clip_box"
  295. "transform" and "clip_path".
  296. """
  297. super().__init__(offset=offset)
  298. self.patch = mpatches.PathPatch([], **kwargs)
  299. def draw_path(self, renderer, gc, tpath, affine, rgbFace):
  300. self.patch._path = tpath
  301. self.patch.set_transform(affine + self._offset_transform(renderer))
  302. self.patch.set_clip_box(gc.get_clip_rectangle())
  303. clip_path = gc.get_clip_path()
  304. if clip_path:
  305. self.patch.set_clip_path(*clip_path)
  306. self.patch.draw(renderer)