不同文本的布局

创建具有不同对齐和旋转的文本。

  1. import matplotlib.pyplot as plt
  2. import matplotlib.patches as patches
  3. # build a rectangle in axes coords
  4. left, width = .25, .5
  5. bottom, height = .25, .5
  6. right = left + width
  7. top = bottom + height
  8. fig = plt.figure()
  9. ax = fig.add_axes([0,0,1,1])
  10. # axes coordinates are 0,0 is bottom left and 1,1 is upper right
  11. p = patches.Rectangle(
  12. (left, bottom), width, height,
  13. fill=False, transform=ax.transAxes, clip_on=False
  14. )
  15. ax.add_patch(p)
  16. ax.text(left, bottom, 'left top',
  17. horizontalalignment='left',
  18. verticalalignment='top',
  19. transform=ax.transAxes)
  20. ax.text(left, bottom, 'left bottom',
  21. horizontalalignment='left',
  22. verticalalignment='bottom',
  23. transform=ax.transAxes)
  24. ax.text(right, top, 'right bottom',
  25. horizontalalignment='right',
  26. verticalalignment='bottom',
  27. transform=ax.transAxes)
  28. ax.text(right, top, 'right top',
  29. horizontalalignment='right',
  30. verticalalignment='top',
  31. transform=ax.transAxes)
  32. ax.text(right, bottom, 'center top',
  33. horizontalalignment='center',
  34. verticalalignment='top',
  35. transform=ax.transAxes)
  36. ax.text(left, 0.5*(bottom+top), 'right center',
  37. horizontalalignment='right',
  38. verticalalignment='center',
  39. rotation='vertical',
  40. transform=ax.transAxes)
  41. ax.text(left, 0.5*(bottom+top), 'left center',
  42. horizontalalignment='left',
  43. verticalalignment='center',
  44. rotation='vertical',
  45. transform=ax.transAxes)
  46. ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
  47. horizontalalignment='center',
  48. verticalalignment='center',
  49. fontsize=20, color='red',
  50. transform=ax.transAxes)
  51. ax.text(right, 0.5*(bottom+top), 'centered',
  52. horizontalalignment='center',
  53. verticalalignment='center',
  54. rotation='vertical',
  55. transform=ax.transAxes)
  56. ax.text(left, top, 'rotated\nwith newlines',
  57. horizontalalignment='center',
  58. verticalalignment='center',
  59. rotation=45,
  60. transform=ax.transAxes)
  61. ax.set_axis_off()
  62. plt.show()

不同文本的布局

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.axes.Axes.text
  3. matplotlib.pyplot.text

下载这个示例