文本路径演示

使用文本作为路径。允许这种转换的工具是 TextPath。可以采用所得的路径,例如,作为图像的剪辑路径。

文本路径演示

  1. import matplotlib.pyplot as plt
  2. from matplotlib.image import BboxImage
  3. import numpy as np
  4. from matplotlib.transforms import IdentityTransform
  5. import matplotlib.patches as mpatches
  6. from matplotlib.offsetbox import AnnotationBbox,\
  7. AnchoredOffsetbox, AuxTransformBox
  8. from matplotlib.cbook import get_sample_data
  9. from matplotlib.text import TextPath
  10. class PathClippedImagePatch(mpatches.PathPatch):
  11. """
  12. The given image is used to draw the face of the patch. Internally,
  13. it uses BboxImage whose clippath set to the path of the patch.
  14. FIXME : The result is currently dpi dependent.
  15. """
  16. def __init__(self, path, bbox_image, **kwargs):
  17. mpatches.PathPatch.__init__(self, path, **kwargs)
  18. self._init_bbox_image(bbox_image)
  19. def set_facecolor(self, color):
  20. """simply ignore facecolor"""
  21. mpatches.PathPatch.set_facecolor(self, "none")
  22. def _init_bbox_image(self, im):
  23. bbox_image = BboxImage(self.get_window_extent,
  24. norm=None,
  25. origin=None,
  26. )
  27. bbox_image.set_transform(IdentityTransform())
  28. bbox_image.set_data(im)
  29. self.bbox_image = bbox_image
  30. def draw(self, renderer=None):
  31. # the clip path must be updated every draw. any solution? -JJ
  32. self.bbox_image.set_clip_path(self._path, self.get_transform())
  33. self.bbox_image.draw(renderer)
  34. mpatches.PathPatch.draw(self, renderer)
  35. if 1:
  36. usetex = plt.rcParams["text.usetex"]
  37. fig = plt.figure(1)
  38. # EXAMPLE 1
  39. ax = plt.subplot(211)
  40. arr = plt.imread(get_sample_data("grace_hopper.png"))
  41. text_path = TextPath((0, 0), "!?", size=150)
  42. p = PathClippedImagePatch(text_path, arr, ec="k",
  43. transform=IdentityTransform())
  44. # p.set_clip_on(False)
  45. # make offset box
  46. offsetbox = AuxTransformBox(IdentityTransform())
  47. offsetbox.add_artist(p)
  48. # make anchored offset box
  49. ao = AnchoredOffsetbox(loc='upper left', child=offsetbox, frameon=True,
  50. borderpad=0.2)
  51. ax.add_artist(ao)
  52. # another text
  53. from matplotlib.patches import PathPatch
  54. if usetex:
  55. r = r"\mbox{textpath supports mathtext \& \TeX}"
  56. else:
  57. r = r"textpath supports mathtext & TeX"
  58. text_path = TextPath((0, 0), r,
  59. size=20, usetex=usetex)
  60. p1 = PathPatch(text_path, ec="w", lw=3, fc="w", alpha=0.9,
  61. transform=IdentityTransform())
  62. p2 = PathPatch(text_path, ec="none", fc="k",
  63. transform=IdentityTransform())
  64. offsetbox2 = AuxTransformBox(IdentityTransform())
  65. offsetbox2.add_artist(p1)
  66. offsetbox2.add_artist(p2)
  67. ab = AnnotationBbox(offsetbox2, (0.95, 0.05),
  68. xycoords='axes fraction',
  69. boxcoords="offset points",
  70. box_alignment=(1., 0.),
  71. frameon=False
  72. )
  73. ax.add_artist(ab)
  74. ax.imshow([[0, 1, 2], [1, 2, 3]], cmap=plt.cm.gist_gray_r,
  75. interpolation="bilinear",
  76. aspect="auto")
  77. # EXAMPLE 2
  78. ax = plt.subplot(212)
  79. arr = np.arange(256).reshape(1, 256)/256.
  80. if usetex:
  81. s = (r"$\displaystyle\left[\sum_{n=1}^\infty"
  82. r"\frac{-e^{i\pi}}{2^n}\right]$!")
  83. else:
  84. s = r"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
  85. text_path = TextPath((0, 0), s, size=40, usetex=usetex)
  86. text_patch = PathClippedImagePatch(text_path, arr, ec="none",
  87. transform=IdentityTransform())
  88. shadow1 = mpatches.Shadow(text_patch, 1, -1,
  89. props=dict(fc="none", ec="0.6", lw=3))
  90. shadow2 = mpatches.Shadow(text_patch, 1, -1,
  91. props=dict(fc="0.3", ec="none"))
  92. # make offset box
  93. offsetbox = AuxTransformBox(IdentityTransform())
  94. offsetbox.add_artist(shadow1)
  95. offsetbox.add_artist(shadow2)
  96. offsetbox.add_artist(text_patch)
  97. # place the anchored offset box using AnnotationBbox
  98. ab = AnnotationBbox(offsetbox, (0.5, 0.5),
  99. xycoords='data',
  100. boxcoords="offset points",
  101. box_alignment=(0.5, 0.5),
  102. )
  103. # text_path.set_size(10)
  104. ax.add_artist(ab)
  105. ax.set_xlim(0, 1)
  106. ax.set_ylim(0, 1)
  107. plt.show()

下载这个示例