演示轴 Hbox Divider

HBox Divider用于排列子图。

演示轴 Hbox Divider

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
  4. import mpl_toolkits.axes_grid1.axes_size as Size
  5. def make_heights_equal(fig, rect, ax1, ax2, pad):
  6. # pad in inches
  7. h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
  8. h2, v2 = Size.AxesX(ax2), Size.AxesY(ax2)
  9. pad_v = Size.Scaled(1)
  10. pad_h = Size.Fixed(pad)
  11. my_divider = HBoxDivider(fig, rect,
  12. horizontal=[h1, pad_h, h2],
  13. vertical=[v1, pad_v, v2])
  14. ax1.set_axes_locator(my_divider.new_locator(0))
  15. ax2.set_axes_locator(my_divider.new_locator(2))
  16. if __name__ == "__main__":
  17. arr1 = np.arange(20).reshape((4, 5))
  18. arr2 = np.arange(20).reshape((5, 4))
  19. fig, (ax1, ax2) = plt.subplots(1, 2)
  20. ax1.imshow(arr1, interpolation="nearest")
  21. ax2.imshow(arr2, interpolation="nearest")
  22. rect = 111 # subplot param for combined axes
  23. make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches
  24. for ax in [ax1, ax2]:
  25. ax.locator_params(nbins=4)
  26. # annotate
  27. ax3 = plt.axes([0.5, 0.5, 0.001, 0.001], frameon=False)
  28. ax3.xaxis.set_visible(False)
  29. ax3.yaxis.set_visible(False)
  30. ax3.annotate("Location of two axes are adjusted\n"
  31. "so that they have equal heights\n"
  32. "while maintaining their aspect ratios", (0.5, 0.5),
  33. xycoords="axes fraction", va="center", ha="center",
  34. bbox=dict(boxstyle="round, pad=1", fc="w"))
  35. plt.show()

下载这个示例