import numpy as np
import matplotlib.pyplot as plt
# 创建数据
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x) + 1
# 创建图形对象和左右两个坐标轴对象
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
# 在左边的坐标轴上绘制sin曲线
ax1.plot(x, y1, label='sin(x)', color='blue')
ax1.set_ylabel('y1', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
# 在右边的坐标轴上绘制cos曲线
ax2.plot(x, y2, label='cos(x) + 1', color='red')
ax2.set_ylabel('y2', color='red')
ax2.tick_params(axis='y', labelcolor='red')
# 设置x轴标签和标题
ax1.set_xlabel('x')
plt.title('Two Y-Axes Plot')
# 合并图例
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(handles1 + handles2, labels1 + labels2)
# 显示图形
plt.show()
效果: