使用多个Y轴绘图

0 投票
1 回答
1141 浏览
提问于 2025-04-18 18:28

在使用 ax.<plot_function> 来绘制图形的时候,怎么才能让图形“保持”在同一个图上,显示多个图呢?

举个例子:

f = plt.figure(figsize=(13,6))
ax = f.add_subplot(111)

ax.plot(x1,y1)
ax.plot(x2,y2)

ax.plot(xN,yN)

我尝试在开始绘图之前加上:

ax.hold(True)

但是这样做没有效果。我觉得问题可能是因为它们都共享同一个y轴的刻度,所以我只能看到数值范围最大的那个图。

那我该怎么在同一个图上绘制多个不同刻度的一维数组呢?有没有办法把它们用不同的Y轴并排显示呢?

1 个回答

2

问题中的代码应该没有什么问题:

import matplotlib.pyplot as plt
import numpy as np

# some data
x1 = np.linspace(0, 10, 100)
x2 = np.linspace(1, 11, 100)
xN = np.linspace(4, 5, 100)
y1 = np.random.random(100)
y2 = 0.5 + np.random.random(100)
yN = 1 + np.random.random(100)![enter image description here][1]

# and then the code in the question
f = plt.figure(figsize=(13,6))
ax = f.add_subplot(111)

ax.plot(x1,y1)
ax.plot(x2,y2)

ax.plot(xN,yN) 

# save the figure
f.savefig("/tmp/test.png")

生成了:

在这里输入图片描述

这应该和预期的差不多。所以问题不在代码上。

你是在命令行中运行这些命令吗?用的是哪个?是IPython吗?

我随便猜一下:这三个图都是绘图,但它们的数据完全相同,所以图形重叠在一起了。

撰写回答