BboxImage 演示

BboxImage可用于根据边界框定位图像。此演示演示如何在text.Text的边界框内显示图像以及如何手动为图像创建边界框。

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.image import BboxImage
  4. from matplotlib.transforms import Bbox, TransformedBbox
  5. fig, (ax1, ax2) = plt.subplots(ncols=2)
  6. # ----------------------------
  7. # Create a BboxImage with Text
  8. # ----------------------------
  9. txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w")
  10. kwargs = dict()
  11. bbox_image = BboxImage(txt.get_window_extent,
  12. norm=None,
  13. origin=None,
  14. clip_on=False,
  15. **kwargs
  16. )
  17. a = np.arange(256).reshape(1, 256)/256.
  18. bbox_image.set_data(a)
  19. ax1.add_artist(bbox_image)
  20. # ------------------------------------
  21. # Create a BboxImage for each colormap
  22. # ------------------------------------
  23. a = np.linspace(0, 1, 256).reshape(1, -1)
  24. a = np.vstack((a, a))
  25. # List of all colormaps; skip reversed colormaps.
  26. maps = sorted(m for m in plt.cm.cmap_d if not m.endswith("_r"))
  27. ncol = 2
  28. nrow = len(maps)//ncol + 1
  29. xpad_fraction = 0.3
  30. dx = 1./(ncol + xpad_fraction*(ncol - 1))
  31. ypad_fraction = 0.3
  32. dy = 1./(nrow + ypad_fraction*(nrow - 1))
  33. for i, m in enumerate(maps):
  34. ix, iy = divmod(i, nrow)
  35. bbox0 = Bbox.from_bounds(ix*dx*(1 + xpad_fraction),
  36. 1. - iy*dy*(1 + ypad_fraction) - dy,
  37. dx, dy)
  38. bbox = TransformedBbox(bbox0, ax2.transAxes)
  39. bbox_image = BboxImage(bbox,
  40. cmap=plt.get_cmap(m),
  41. norm=None,
  42. origin=None,
  43. **kwargs
  44. )
  45. bbox_image.set_data(a)
  46. ax2.add_artist(bbox_image)
  47. plt.show()

BboxImage 演示

参考

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

  1. import matplotlib
  2. matplotlib.image.BboxImage
  3. matplotlib.transforms.Bbox
  4. matplotlib.transforms.TransformedBbox
  5. matplotlib.text.Text

下载这个示例