matlab如何设置legend
时间: 2025-05-17 13:26:27 浏览: 123
### Matlab 中设置 Legend 的方法
在 MATLAB 中,`legend` 函数用于创建图形中的图例。通过 `legend` 可以为每一条绘制的曲线指定标签,并支持多种自定义选项,例如位置调整、字体大小修改以及去除边框等。
以下是关于如何在 MATLAB 中设置 `legend` 的具体说明和示例:
#### 基本语法
最简单的调用方式如下所示:
```matlab
legend('Label1', 'Label2', ...);
```
如果需要更复杂的控制,则可以使用带有属性参数的方式:
```matlab
h = legend({'Label1', 'Label2'}, 'Location', 'northoutside');
set(h, 'FontSize', 12, 'EdgeColor', 'none'); % 修改字体大小并移除边框
```
---
#### 自定义 Legend 属性
可以通过以下几种方式进行进一步定制化操作:
1. **Legend 的位置**
使用 `'Location'` 参数来设定图例的位置。常见的位置有 `'NorthOutside'`, `'SouthEast'`, 或者其他方向[^2]。
示例代码:
```matlab
t = linspace(0, 2*pi, 100);
y1 = sin(t);
y2 = cos(t);
plot(t, y1, 'r-', t, y2, 'b--');
h = legend('Sine Wave', 'Cosine Wave', 'Location', 'northeast');
```
2. **去掉 Legend 边框**
如果希望隐藏图例外部的矩形边界线,可将其颜色设为透明[^1]:
```matlab
set(h, 'EdgeColor', 'none');
```
3. **更改 FontSize 和 字体样式**
调整图例文字显示效果也是常用需求之一。比如增大字号以便于阅读或者改变字型风格。
```matlab
set(h, 'FontSize', 14, 'FontWeight', 'bold');
```
4. **动态添加 DisplayName**
当有多条数据绘图时,可以直接利用 `'DisplayName'` 来简化流程而无需单独调用一次 `legend()` 函数[^4].
```matlab
x = linspace(-pi, pi, 100);
y1 = sin(x); y2 = cos(x);
y3 = tan(x/2); y4 = exp(-abs(x));
figure;
hold on;
plot(x, y1, '-r', 'DisplayName','Sin(x)');
plot(x, y2, '--b', 'DisplayName','Cos(x)');
plot(x, y3, ':g', 'DisplayName','Tan(x/2)');
plot(x, y4, '.k', 'DisplayName','Exp(-|x|)');
lgd = legend; % 自动生成对应名称作为 label
set(lgd,'Box','off') ;% 关闭外接方框
```
5. **批量处理多个子图 Legends**
对于含有若干个子窗口的情况,可能需要用到循环结构逐一配置各部分 legends[^3].
---
### 完整综合实例
下面给出一个完整的例子展示上述功能的应用场景:
```matlab
clc; clear all; close all;
fs = 1e3; % Sampling Frequency (Hz)
t = 0:1/fs:1; % Time Vector (seconds)
frequencies = [5, 10]; amplitudes = [7, 3];
colors = {'magenta', 'cyan'};
styles = {'-.', ':'};
figure('Name', 'Multiple Signals with Customized Legends'), hold on,
for idx=1:length(frequencies),
freq = frequencies(idx);
amp = amplitudes(idx);
signal = amp*sin(2*pi*freq*t);
colorStr = colors{idx};
styleChar = styles{idx};
plot(t,signal,[colorStr styleChar],'LineWidth',1.5,...
'DisplayName',['Signal ',num2str(freq),' Hz']);
end
lgdHandle = legend('show'); % Show the default legend.
title(lgdHandle,'Signals Overview'); % Add title to legend box.
% Customize appearance of legend object:
set(lgdHandle,'Interpreter','latex',...
'FontSize',12,...
'FontAngle','italic',...
'EdgeColor',[0.8 0.8 0.8],... % Light gray border around it.
'Position',[0.65 0.65 0.25 0.2]); % Move & resize manually here!
hold off;
grid minor;
xlabel('$Time\,(sec)$','interpreter','latex');
ylabel('$Amplitude$','interpreter','latex');
```
此脚本不仅实现了基本的功能演示还包含了高级特性如 LaTeX 解析器的支持使得图表更加美观专业。
---
阅读全文
相关推荐


















