同一轴上的不同比例

演示如何在左右y轴上显示两个刻度。

此示例使用华氏度和摄氏度量表。

同一轴上的不同比例示例

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. def fahrenheit2celsius(temp):
  4. """
  5. Returns temperature in Celsius.
  6. """
  7. return (5. / 9.) * (temp - 32)
  8. def convert_ax_c_to_celsius(ax_f):
  9. """
  10. Update second axis according with first axis.
  11. """
  12. y1, y2 = ax_f.get_ylim()
  13. ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))
  14. ax_c.figure.canvas.draw()
  15. fig, ax_f = plt.subplots()
  16. ax_c = ax_f.twinx()
  17. # automatically update ylim of ax2 when ylim of ax1 changes.
  18. ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)
  19. ax_f.plot(np.linspace(-40, 120, 100))
  20. ax_f.set_xlim(0, 100)
  21. ax_f.set_title('Two scales: Fahrenheit and Celsius')
  22. ax_f.set_ylabel('Fahrenheit')
  23. ax_c.set_ylabel('Celsius')
  24. plt.show()

下载这个示例