自动文本偏移

演示如何使用pathpatch_2d_to_3d在3D绘图上“绘制”形状和文本。

自动文本偏移示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.patches import Circle, PathPatch
  4. from matplotlib.text import TextPath
  5. from matplotlib.transforms import Affine2D
  6. # This import registers the 3D projection, but is otherwise unused.
  7. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
  8. import mpl_toolkits.mplot3d.art3d as art3d
  9. def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
  10. '''
  11. Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
  12. and rotation angle 'angle'. 'zdir' gives the axis which is to be treated
  13. as the third dimension. usetex is a boolean indicating whether the string
  14. should be interpreted as latex or not. Any additional keyword arguments
  15. are passed on to transform_path.
  16. Note: zdir affects the interpretation of xyz.
  17. '''
  18. x, y, z = xyz
  19. if zdir == "y":
  20. xy1, z1 = (x, z), y
  21. elif zdir == "x":
  22. xy1, z1 = (y, z), x
  23. else:
  24. xy1, z1 = (x, y), z
  25. text_path = TextPath((0, 0), s, size=size, usetex=usetex)
  26. trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
  27. p1 = PathPatch(trans.transform_path(text_path), **kwargs)
  28. ax.add_patch(p1)
  29. art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
  30. fig = plt.figure()
  31. ax = fig.add_subplot(111, projection='3d')
  32. # Draw a circle on the x=0 'wall'
  33. p = Circle((5, 5), 3)
  34. ax.add_patch(p)
  35. art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
  36. # Manually label the axes
  37. text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False,
  38. ec="none", fc="k")
  39. text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False,
  40. angle=np.pi / 2, ec="none", fc="k")
  41. text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False,
  42. angle=np.pi / 2, ec="none", fc="k")
  43. # Write a Latex formula on the z=0 'floor'
  44. text3d(ax, (1, 5, 0),
  45. r"$\displaystyle G_{\mu\nu} + \Lambda g_{\mu\nu} = "
  46. r"\frac{8\pi G}{c^4} T_{\mu\nu} $",
  47. zdir="z", size=1, usetex=True,
  48. ec="none", fc="k")
  49. ax.set_xlim(0, 10)
  50. ax.set_ylim(0, 10)
  51. ax.set_zlim(0, 10)
  52. plt.show()

下载这个示例