插入定位器演示2

本演示展示了如何通过 zoomed_inset_axes 创建缩放插图。 在第一个子图中,AnchoredSizeBar 显示缩放效果。 在第二个子图中,通过mark_inset 创建与感兴趣区域的连接。

插入定位器演示2

  1. import matplotlib.pyplot as plt
  2. from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
  3. from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
  4. import numpy as np
  5. def get_demo_image():
  6. from matplotlib.cbook import get_sample_data
  7. import numpy as np
  8. f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
  9. z = np.load(f)
  10. # z is a numpy array of 15x15
  11. return z, (-3, 4, -4, 3)
  12. fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])
  13. # First subplot, showing an inset with a size bar.
  14. ax.set_aspect(1)
  15. axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')
  16. # fix the number of ticks on the inset axes
  17. axins.yaxis.get_major_locator().set_params(nbins=7)
  18. axins.xaxis.get_major_locator().set_params(nbins=7)
  19. plt.setp(axins.get_xticklabels(), visible=False)
  20. plt.setp(axins.get_yticklabels(), visible=False)
  21. def add_sizebar(ax, size):
  22. asb = AnchoredSizeBar(ax.transData,
  23. size,
  24. str(size),
  25. loc=8,
  26. pad=0.1, borderpad=0.5, sep=5,
  27. frameon=False)
  28. ax.add_artist(asb)
  29. add_sizebar(ax, 0.5)
  30. add_sizebar(axins, 0.5)
  31. # Second subplot, showing an image with an inset zoom
  32. # and a marked inset
  33. Z, extent = get_demo_image()
  34. Z2 = np.zeros([150, 150], dtype="d")
  35. ny, nx = Z.shape
  36. Z2[30:30 + ny, 30:30 + nx] = Z
  37. # extent = [-3, 4, -4, 3]
  38. ax2.imshow(Z2, extent=extent, interpolation="nearest",
  39. origin="lower")
  40. axins2 = zoomed_inset_axes(ax2, 6, loc=1) # zoom = 6
  41. axins2.imshow(Z2, extent=extent, interpolation="nearest",
  42. origin="lower")
  43. # sub region of the original image
  44. x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
  45. axins2.set_xlim(x1, x2)
  46. axins2.set_ylim(y1, y2)
  47. # fix the number of ticks on the inset axes
  48. axins2.yaxis.get_major_locator().set_params(nbins=7)
  49. axins2.xaxis.get_major_locator().set_params(nbins=7)
  50. plt.setp(axins2.get_xticklabels(), visible=False)
  51. plt.setp(axins2.get_yticklabels(), visible=False)
  52. # draw a bbox of the region of the inset axes in the parent axes and
  53. # connecting lines between the bbox and the inset axes area
  54. mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")
  55. plt.show()

下载这个示例