绘制不同比例
在同一轴上的两个图样,具有不同的左右比例。
诀窍是使用共享同一x轴的两个不同的轴。您可以根据需要使用单独的 matplotlib.ticker 格式化程序和定位器,因为这两个轴是独立的。
这些轴是通过调用 Axes.twinx() 方法生成的。同样,Axes.twiny() 可用于生成共享y轴但具有不同顶部和底部比例的轴。
import numpy as npimport matplotlib.pyplot as plt# Create some mock datat = np.arange(0.01, 10.0, 0.01)data1 = np.exp(t)data2 = np.sin(2 * np.pi * t)fig, ax1 = plt.subplots()color = 'tab:red'ax1.set_xlabel('time (s)')ax1.set_ylabel('exp', color=color)ax1.plot(t, data1, color=color)ax1.tick_params(axis='y', labelcolor=color)ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axiscolor = 'tab:blue'ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1ax2.plot(t, data2, color=color)ax2.tick_params(axis='y', labelcolor=color)fig.tight_layout() # otherwise the right y-label is slightly clippedplt.show()

参考
此示例显示了以下函数、方法、类和模块的使用:
import matplotlibmatplotlib.axes.Axes.twinxmatplotlib.axes.Axes.twinymatplotlib.axes.Axes.tick_params
