多个Yaxis与Spines

使用共享x轴创建多个y轴。这是通过创建一个双轴,转动所有脊柱但右边的一个不可见并使用set_position偏移其位置来完成的。

请注意,此方法使用 matplotlib.axes.Axes 及其Spines。 寄生虫轴的另一种方法显示在Demo Parasite AxesDemo Parasite Axes2示例中。

多个Yaxis与Spines示例

  1. import matplotlib.pyplot as plt
  2. def make_patch_spines_invisible(ax):
  3. ax.set_frame_on(True)
  4. ax.patch.set_visible(False)
  5. for sp in ax.spines.values():
  6. sp.set_visible(False)
  7. fig, host = plt.subplots()
  8. fig.subplots_adjust(right=0.75)
  9. par1 = host.twinx()
  10. par2 = host.twinx()
  11. # Offset the right spine of par2. The ticks and label have already been
  12. # placed on the right by twinx above.
  13. par2.spines["right"].set_position(("axes", 1.2))
  14. # Having been created by twinx, par2 has its frame off, so the line of its
  15. # detached spine is invisible. First, activate the frame but make the patch
  16. # and spines invisible.
  17. make_patch_spines_invisible(par2)
  18. # Second, show the right spine.
  19. par2.spines["right"].set_visible(True)
  20. p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
  21. p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
  22. p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
  23. host.set_xlim(0, 2)
  24. host.set_ylim(0, 2)
  25. par1.set_ylim(0, 4)
  26. par2.set_ylim(1, 65)
  27. host.set_xlabel("Distance")
  28. host.set_ylabel("Density")
  29. par1.set_ylabel("Temperature")
  30. par2.set_ylabel("Velocity")
  31. host.yaxis.label.set_color(p1.get_color())
  32. par1.yaxis.label.set_color(p2.get_color())
  33. par2.yaxis.label.set_color(p3.get_color())
  34. tkw = dict(size=4, width=1.5)
  35. host.tick_params(axis='y', colors=p1.get_color(), **tkw)
  36. par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
  37. par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
  38. host.tick_params(axis='x', **tkw)
  39. lines = [p1, p2, p3]
  40. host.legend(lines, [l.get_label() for l in lines])
  41. plt.show()

下载这个示例