matlab legend()函数
的有关信息介绍如下:
在 MATLAB 中,legend() 函数用于为图形添加图例,图例可以帮助识别图中的不同数据系列或曲线。以下是 legend() 函数的一些基本用法和示例:
基本用法
假设你已经绘制了一些数据,比如:
x = linspace(0, 2*pi, 100); y1 = sin(x); y2 = cos(x); plot(x, y1, '-r', 'DisplayName', 'sin(x)'); % '-r' 表示红色实线 hold on; plot(x, y2, '--b', 'DisplayName', 'cos(x)'); % '--b' 表示蓝色虚线 hold off;在这种情况下,你可以使用 legend() 函数自动从 DisplayName 属性中提取图例标签:
legend;这将生成一个包含 "sin(x)" 和 "cos(x)" 的图例。
手动指定图例项
如果你没有使用 DisplayName 属性,或者想手动指定图例项,可以这样做:
plot(x, y1, '-r'); hold on; plot(x, y2, '--b'); hold off; legend('sin(x)', 'cos(x)');指定图例位置
你可以通过第二个参数指定图例的位置。常用的位置选项包括:
- 'north'(默认)
- 'south'
- 'east'
- 'west'
- 'northeast'
- 'northwest'
- 'southeast'
- 'southwest'
- 'best'(MATLAB 自动选择最佳位置)
- 'bestoutside'(类似于 'best',但图例在图形边界外)
例如:
legend('sin(x)', 'cos(x)', 'Location', 'northwest');控制图例的显示属性
你可以通过 legend 对象的属性来进一步控制图例的显示,比如字体大小、颜色等。例如:
lgd = legend('sin(x)', 'cos(x)'); lgd.FontSize = 12; % 设置字体大小 lgd.Box = 'on'; % 添加图例框完整示例
下面是一个完整的示例,展示了如何绘制数据并添加图例:
% 数据准备 x = linspace(0, 2*pi, 100); y1 = sin(x); y2 = cos(x); % 绘图 plot(x, y1, '-r', 'DisplayName', 'sin(x)'); hold on; plot(x, y2, '--b', 'DisplayName', 'cos(x)'); hold off; % 添加图例 legend('Location', 'northwest', 'FontSize', 12, 'Box', 'on'); % 添加标题和标签 title('Sine and Cosine Functions'); xlabel('x'); ylabel('y');通过上述方法,你可以灵活地在 MATLAB 图形中添加和控制图例。



