双折现双坐标图Python
时间: 2025-04-25 20:37:06 浏览: 12
### 使用 Python Matplotlib 绘制双 Y 轴折线图
为了创建具有两个不同 Y 轴的图表,通常会使用 `twinx()` 方法来获取共享相同 X 轴但拥有独立 Y 轴的第二个坐标系。以下是具体实现方法:
#### 导入库
首先导入必要的库,包括用于数值计算的 NumPy 和 Pandas 以及绘图工具 Matplotlib。
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
```
#### 设置全局样式配置
为了让图形更加美观,可以通过修改 Rc 参数来自定义字体和其他显示属性。
```python
config = {
"font.family": ["Times New Roman", "SimSun"],
"font.size": 12,
"mathtext.fontset": 'stix',
"font.serif": ["Times New Roman", "SimSun"]
}
rcParams.update(config)
```
#### 准备数据
假设有一个 Excel 文件包含了随时间变化的人口数量和 GDP 数据,则可通过 Pandas 来加载这些数据。
```python
data = pd.read_excel("data.xlsx")
x = data['时间'].values
y1 = data['人口'].values
y2 = data['GDP'].values
```
#### 创建图形对象并绘制第一条折线
初始化一个新的 Figure 对象,并通过调用其 subplot 或 add_subplot 方法获得 Axes 实例来进行实际作图操作。
```python
fig, ax1 = plt.subplots()
color = '#6AA84F'
ax1.set_xlabel('年份')
ax1.set_ylabel('人口 (单位)', color=color)
ax1.plot(x, y1, label='人口', color=color)
ax1.tick_params(axis='y', labelcolor=color)
plt.legend(loc='upper left')
```
#### 添加第二条折线及其对应的右侧 Y 轴标签
利用第一个 Axes 的 twinx() 方法得到另一个与之关联的新 Axes,该 Axes 将被用来表示另一组不同的数据系列。
```python
ax2 = ax1.twinx()
color = '#5470C6'
ax2.set_ylabel('GDP (亿元)', color=color)
ax2.plot(x, y2, label='GDP', linestyle="--", color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.legend(loc='lower right')
```
最后一步是展示所构建好的图表。
```python
plt.title('中国历年经济和社会发展情况对比')
plt.show()
```
上述过程展示了如何在一个窗口内同时呈现两套相互关联却又尺度各异的数据序列[^3]。
阅读全文
相关推荐


















