具有不同刻度的绘图#

在同一个坐标轴(Axes)上有两个绘图,左右两侧具有不同的刻度。

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

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

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

标签:组件:坐标轴 绘图类型:折线图 级别:初学者

脚本总运行时间: (0 分钟 1.039 秒)

由 Sphinx-Gallery 生成的画廊