图中插入注释框

图中插入注释框示例

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.patches import Circle
  4. from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
  5. AnnotationBbox)
  6. from matplotlib.cbook import get_sample_data
  7. if 1:
  8. fig, ax = plt.subplots()
  9. # Define a 1st position to annotate (display it with a marker)
  10. xy = (0.5, 0.7)
  11. ax.plot(xy[0], xy[1], ".r")
  12. # Annotate the 1st position with a text box ('Test 1')
  13. offsetbox = TextArea("Test 1", minimumdescent=False)
  14. ab = AnnotationBbox(offsetbox, xy,
  15. xybox=(-20, 40),
  16. xycoords='data',
  17. boxcoords="offset points",
  18. arrowprops=dict(arrowstyle="->"))
  19. ax.add_artist(ab)
  20. # Annotate the 1st position with another text box ('Test')
  21. offsetbox = TextArea("Test", minimumdescent=False)
  22. ab = AnnotationBbox(offsetbox, xy,
  23. xybox=(1.02, xy[1]),
  24. xycoords='data',
  25. boxcoords=("axes fraction", "data"),
  26. box_alignment=(0., 0.5),
  27. arrowprops=dict(arrowstyle="->"))
  28. ax.add_artist(ab)
  29. # Define a 2nd position to annotate (don't display with a marker this time)
  30. xy = [0.3, 0.55]
  31. # Annotate the 2nd position with a circle patch
  32. da = DrawingArea(20, 20, 0, 0)
  33. p = Circle((10, 10), 10)
  34. da.add_artist(p)
  35. ab = AnnotationBbox(da, xy,
  36. xybox=(1.02, xy[1]),
  37. xycoords='data',
  38. boxcoords=("axes fraction", "data"),
  39. box_alignment=(0., 0.5),
  40. arrowprops=dict(arrowstyle="->"))
  41. ax.add_artist(ab)
  42. # Annotate the 2nd position with an image (a generated array of pixels)
  43. arr = np.arange(100).reshape((10, 10))
  44. im = OffsetImage(arr, zoom=2)
  45. im.image.axes = ax
  46. ab = AnnotationBbox(im, xy,
  47. xybox=(-50., 50.),
  48. xycoords='data',
  49. boxcoords="offset points",
  50. pad=0.3,
  51. arrowprops=dict(arrowstyle="->"))
  52. ax.add_artist(ab)
  53. # Annotate the 2nd position with another image (a Grace Hopper portrait)
  54. fn = get_sample_data("grace_hopper.png", asfileobj=False)
  55. arr_img = plt.imread(fn, format='png')
  56. imagebox = OffsetImage(arr_img, zoom=0.2)
  57. imagebox.image.axes = ax
  58. ab = AnnotationBbox(imagebox, xy,
  59. xybox=(120., -80.),
  60. xycoords='data',
  61. boxcoords="offset points",
  62. pad=0.5,
  63. arrowprops=dict(
  64. arrowstyle="->",
  65. connectionstyle="angle,angleA=0,angleB=90,rad=3")
  66. )
  67. ax.add_artist(ab)
  68. # Fix the display limits to see everything
  69. ax.set_xlim(0, 1)
  70. ax.set_ylim(0, 1)
  71. plt.show()

下载这个示例