MATLAB多曲线是在同一坐标系里画多条线,方便直接对比。量纲差得大、或者要并排摆多个独立图时,再用 subplot 把窗口切成格子,各画各的。

叠在同一张图:一次 plot 多组

x = 0:0.01:10;
plot(x, sin(x), x, cos(x), '.-')
legend('Sin(x)', 'Cos(x)')

plot(x1, y1, x2, y2, ...) 每两组 x、y 是一条曲线。legend 里的文字顺序必须和曲线出现的顺序一致。

也可以用 hold on 分几次往同一张图里追加:

x = 0:0.01:10;
plot(x, sin(x), 'r')
hold on
plot(x, cos(x), 'b--')
hold off
legend('sin', 'cos')

hold on 表示保留当前图形继续画,画完用 hold off 放开。

subplot:一张图分成格子

subplot(m, n, p) 把图形窗口分成 m 行 n 列,p 是当前画到第几个格子:

x = 0:0.01:5;
y1 = exp(-1.5*x) .* sin(10*x);
y2 = exp(-2*x) .* sin(10*x);

subplot(1, 2, 1)
plot(x, y1), xlabel('x'), ylabel('exp(-1.5x)sin(10x)'), axis([0 5 -1 1])

subplot(1, 2, 2)
plot(x, y2), xlabel('x'), ylabel('exp(-2x)sin(10x)'), axis([0 5 -1 1])

每个子图是独立坐标系,可以有自己的标题、标签和坐标范围。

2×2 的布局

subplot(2, 2, p) 是 2 行 2 列共 4 个格子,p 按先左后右、先上后下编号:

x = 0:0.01:2*pi;
subplot(2,2,1), plot(x, sin(x)),   title('sin')
subplot(2,2,2), plot(x, cos(x)),   title('cos')
subplot(2,2,3), plot(x, x.^2/20),  title('x^2')
subplot(2,2,4), plot(x, exp(-x)),  title('e^-x')

叠画还是分格

场景选哪个
几条曲线量纲相同,想直接对比趋势同一张图 + legend
量纲差异大,各自细节要看清楚subplot 分格
一份材料里要摆多个独立图表subplot 分格

常见错误

  • 忘了 hold off:下一张图会叠在旧图上,越画越乱。
  • legend 顺序写反:图例按 plot 出现顺序对应,对不上就会张冠李戴。
  • subplot 编号搞错:2×2 里 1 是左上、2 是右上、3 是左下、4 是右下,容易把 3 当成右下。