python画双y轴折线图
时间: 2023-08-03 16:04:23 浏览: 89
要在Python中绘制双Y轴折线图,可以使用Matplotlib库。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 9]
y2 = [50, 30, 15, 10, 5]
# 创建图形和轴对象
fig, ax1 = plt.subplots()
# 绘制第一个Y轴的折线图
ax1.plot(x, y1, 'g-')
ax1.set_xlabel('X轴')
ax1.set_ylabel('Y1轴', color='g')
ax1.tick_params('y', colors='g')
# 创建第二个Y轴对象
ax2 = ax1.twinx()
# 绘制第二个Y轴的折线图
ax2.plot(x, y2, 'b-')
ax2.set_ylabel('Y2轴', color='b')
ax2.tick_params('y', colors='b')
# 添加图例
ax1.legend(['Y1轴'], loc='upper left')
ax2.legend(['Y2轴'], loc='upper right')
# 显示图形
plt.show()
```
这段代码会生成一个带有双Y轴的折线图,其中一个Y轴在左侧,另一个在右侧。Y1轴的折线图用绿色表示,Y2轴的折线图用蓝色表示。你可以根据需要修改数据和其他绘图参数来适应你的需求。
相关问题
python 双y轴折线图
Python中可以使用Matplotlib库来绘制双Y轴的折线图。
首先,我们需要导入Matplotlib库,并设置图表的大小和标题:
```python
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(8, 6))
plt.title("双Y轴折线图")
```
然后,我们可以创建两个Y轴的数据数组,并绘制对应的折线图:
```python
x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 8]
y2 = [100, 50, 70, 80, 90]
ax1.plot(x, y1, color='blue', label='Y1轴')
ax1.set_xlabel('X轴')
ax1.set_ylabel('Y1轴')
ax2 = ax1.twinx() # 创建第二个Y轴
ax2.plot(x, y2, color='red', label='Y2轴')
ax2.set_ylabel('Y2轴')
```
接下来,我们可以设置图例、Y轴刻度和网格线:
```python
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
ax1.tick_params(axis='y', color='blue')
ax2.tick_params(axis='y', color='red')
ax1.grid(True)
```
最后,使用plt.show()方法显示图表:
```python
plt.show()
```
这样就可以在Python中绘制出双Y轴的折线图了。
python 画双y轴图
可以使用matplotlib库来画双y轴图,代码示例如下:
```python
import matplotlib.pyplot as plt
# 创建画布
fig, ax1 = plt.subplots()
# 绘制第一个y轴数据
x1 = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
ax1.plot(x1, y1, 'b-', label='y1')
ax1.set_xlabel('X')
ax1.set_ylabel('y1')
ax1.tick_params('y', colors='b')
# 绘制第二个y轴数据
ax2 = ax1.twinx()
x2 = [1, 2, 3, 4, 5]
y2 = [100, 200, 300, 400, 500]
ax2.plot(x2, y2, 'r-', label='y2')
ax2.set_ylabel('y2', color='r')
ax2.tick_params('y', colors='r')
# 添加图例
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='best')
plt.show()
```
这段代码实现的是画一个包含两组数据的双y轴折线图。其中,第一组数据用蓝色线表示,对应左侧y轴;第二组数据用红色线表示,对应右侧y轴。如果需要画其他类型的双y轴图,可以根据实际需求进行修改。