如何实现 Python 折线图双y轴

1. 了解需求

首先,我们需要了解如何在 Python 中创建折线图并添加双y轴。

2. 准备工作

在开始之前,确保已经安装了 matplotlib 库,如果没有安装,可以使用以下命令安装:

pip install matplotlib

3. 创建折线图

接下来,我们来创建一个简单的折线图,代码如下:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [10, 15, 13, 18, 16]

plt.plot(x, y1, label='y1', color='blue')
plt.xlabel('X轴')
plt.ylabel('Y轴1')
plt.legend()
plt.show()

这段代码会创建一个包含 y1 轴的折线图。

4. 添加双y轴

现在,我们来添加第二个 y 轴,代码如下:

y2 = [20, 25, 23, 28, 26]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, label='y1', color='blue')
ax2.plot(x, y2, label='y2', color='red')

ax1.set_xlabel('X轴')
ax1.set_ylabel('Y轴1', color='blue')
ax2.set_ylabel('Y轴2', color='red')

plt.legend()
plt.show()

这段代码会在现有折线图的基础上添加一个 y2 轴,实现双y轴效果。

5. 完整代码示例

综合以上内容,下面是实现折线图双y轴的完整代码示例:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [10, 15, 13, 18, 16]
y2 = [20, 25, 23, 28, 26]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, label='y1', color='blue')
ax2.plot(x, y2, label='y2', color='red')

ax1.set_xlabel('X轴')
ax1.set_ylabel('Y轴1', color='blue')
ax2.set_ylabel('Y轴2', color='red')

plt.legend()
plt.show()

6. 总结

通过以上步骤,我们成功实现了在 Python 中创建折线图并添加双y轴的功能。希望这篇文章能够帮助到你理解并实现这一功能。

gantt
    title Python 折线图双y轴实现流程
    section 了解需求 :done, des1, 2023-10-01, 1d
    section 准备工作 :done, des2, after des1, 1d
    section 创建折线图 :done, des3, after des2, 2d
    section 添加双y轴 :done, des4, after des3, 2d
    section 完整代码示例 :done, des5, after des4, 1d
journey
    title Python 折线图双y轴实现步骤
    section 了解需求
    section 准备工作
    section 创建折线图
    section 添加双y轴
    section 完整代码示例

希望你能通过这篇文章顺利实现 Python 折线图双y轴的功能,加油!