Python中matplotlib.pyplot中的twinx()函数

Python中matplotlib.pyplot中的twinx()函数

twin:孪生,双胞胎。

ax2 = ax1.twinx() # 将ax1的x轴也分配给ax2使用

同理,twiny()也是一样的理解。

例1.同时画出f(x)=sin(x)与f(x)=cos(x)图像。

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots(1, 1)
# 让2个子图的x轴一样,同时创建副坐标轴。
ax2 = ax1.twinx()

# 作y = sin(x)函数
x1 = np.linspace(-4 * np.pi, 4 * np.pi, 256)
y1 = np.sin(x1)
ax1.plot(x1, y1, color='red')

# 作y = cos(x)函数
x2 = np.linspace(-4 * np.pi, 4 * np.pi, 256)
y2 = np.cos(x2)
ax2.plot(x2, y2, color='green')

plt.show()

结果如下图所示:
在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_44359479/article/details/115549049