精确文本布局

你可以在数据或轴 (0, 1) 坐标中精确布局文本。此示例显示了文本布局的一些对齐和旋转规范。

精确文本布局示例

  1. import matplotlib.pyplot as plt
  2. # Build a rectangle in axes coords
  3. left, width = .25, .5
  4. bottom, height = .25, .5
  5. right = left + width
  6. top = bottom + height
  7. ax = plt.gca()
  8. p = plt.Rectangle((left, bottom), width, height, fill=False)
  9. p.set_transform(ax.transAxes)
  10. p.set_clip_on(False)
  11. ax.add_patch(p)
  12. ax.text(left, bottom, 'left top',
  13. horizontalalignment='left',
  14. verticalalignment='top',
  15. transform=ax.transAxes)
  16. ax.text(left, bottom, 'left bottom',
  17. horizontalalignment='left',
  18. verticalalignment='bottom',
  19. transform=ax.transAxes)
  20. ax.text(right, top, 'right bottom',
  21. horizontalalignment='right',
  22. verticalalignment='bottom',
  23. transform=ax.transAxes)
  24. ax.text(right, top, 'right top',
  25. horizontalalignment='right',
  26. verticalalignment='top',
  27. transform=ax.transAxes)
  28. ax.text(right, bottom, 'center top',
  29. horizontalalignment='center',
  30. verticalalignment='top',
  31. transform=ax.transAxes)
  32. ax.text(left, 0.5 * (bottom + top), 'right center',
  33. horizontalalignment='right',
  34. verticalalignment='center',
  35. rotation='vertical',
  36. transform=ax.transAxes)
  37. ax.text(left, 0.5 * (bottom + top), 'left center',
  38. horizontalalignment='left',
  39. verticalalignment='center',
  40. rotation='vertical',
  41. transform=ax.transAxes)
  42. ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
  43. horizontalalignment='center',
  44. verticalalignment='center',
  45. transform=ax.transAxes)
  46. ax.text(right, 0.5 * (bottom + top), 'centered',
  47. horizontalalignment='center',
  48. verticalalignment='center',
  49. rotation='vertical',
  50. transform=ax.transAxes)
  51. ax.text(left, top, 'rotated\nwith newlines',
  52. horizontalalignment='center',
  53. verticalalignment='center',
  54. rotation=45,
  55. transform=ax.transAxes)
  56. plt.axis('off')
  57. plt.show()

下载这个示例