不同尺度的图表#

在同一 Axes 上绘制两个具有不同左右尺度的图。

诀窍是使用 两个不同的 Axes ,它们共享同一个 x 轴。由于两个 Axes 是独立的,你可以根据需要使用单独的 matplotlib.ticker 格式化器和定位器。

这种轴是通过调用 Axes.twinx 方法生成的。同样,Axes.twiny 可用于生成共享 y 轴但具有不同上下刻度的轴。

import matplotlib.pyplot as plt
import numpy as np

# Create some mock data
t = 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-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()
two scales

由 Sphinx-Gallery 生成的图库