要在所有子图上方添加一个图例(legend),可以使用以下步骤:
1.为每个子图添加一个标签(label):在绘制每个子图时,使用“label”参数来设置每个曲线的标签。例如:plot(x,y,'label','曲线1')。
2.合并所有的标签(label):在所有的子图都绘制完成后,使用“h”变量来捕获每个子图的句柄(handle),并将所有的标签合并成一个单一的字符串,如下所示:
h = findobj(gcf,'type','axes');
allLabels = [];
for i = 1:length(h)
allLabels = [allLabels, h(i).Children];
end
labels = {allLabels.DisplayName};
3.将图例添加到顶部:最后,使用“legend”函数将标签添加到顶部。注意,需要将标签的字符串数组作为第一个参数传递给“legend”函数。
legend(labels,'Location','northoutside','Orientation','horizontal')
完整的代码示例如下所示:
% 绘制第一个子图
subplot(2,2,1)
x = 0:0.1:pi;
y = sin(x);
plot(x,y,'DisplayName','曲线1')
legend('show')
% 绘制第二个子图
subplot(2,2,2)
x = 0:0.1:pi;
y = cos(x);
plot(x,y,'DisplayName','曲线2')
legend('show')
% 绘制第三个子图
subplot(2,2,3)
x = 0:0.1:pi;
y = tan(x);
plot(x,y,'DisplayName','曲线3')
legend('show')
% 绘制第四个子图
subplot(2,2,4)
x = 0:0.1:pi;
y = exp(x);
plot(x,y,'DisplayName','曲线4')
legend('show')
% 添加图例到所有子图上方
h = findobj(gcf,'type','axes');
allLabels = [];
for i = 1:length(h)
allLabels = [allLabels, h(i).Children];
end
labels = {allLabels.DisplayName};
legend(labels,'Location','northoutside','Orientation','horizontal')