绘制不同比例

在同一轴上的两个图样,具有不同的左右比例。

诀窍是使用共享同一x轴的两个不同的轴。您可以根据需要使用单独的 matplotlib.ticker 格式化程序和定位器,因为这两个轴是独立的。

这些轴是通过调用 Axes.twinx() 方法生成的。同样,Axes.twiny() 可用于生成共享y轴但具有不同顶部和底部比例的轴。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Create some mock data
  4. t = np.arange(0.01, 10.0, 0.01)
  5. data1 = np.exp(t)
  6. data2 = np.sin(2 * np.pi * t)
  7. fig, ax1 = plt.subplots()
  8. color = 'tab:red'
  9. ax1.set_xlabel('time (s)')
  10. ax1.set_ylabel('exp', color=color)
  11. ax1.plot(t, data1, color=color)
  12. ax1.tick_params(axis='y', labelcolor=color)
  13. ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
  14. color = 'tab:blue'
  15. ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
  16. ax2.plot(t, data2, color=color)
  17. ax2.tick_params(axis='y', labelcolor=color)
  18. fig.tight_layout() # otherwise the right y-label is slightly clipped
  19. plt.show()

绘制不同尺度示例

参考

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

  1. import matplotlib
  2. matplotlib.axes.Axes.twinx
  3. matplotlib.axes.Axes.twiny
  4. matplotlib.axes.Axes.tick_params

下载这个示例