To add a legend above all subgraphs, use the following steps:
1. Add a label for each subgraph: When drawing each subgraph, use the "label" parameter to set the label for each curve. Example: plot(x,y,'label',' curve 1').
2. Merge all labels: After all subgraphs are drawn, use the "h" variable to capture the handle of each subgraph and combine all labels into a single string, as follows:
h = findobj(gcf,'type','axes');
allLabels = [];
for i = 1:length(h)
allLabels = [allLabels, h(i).Children];
end
labels = {allLabels.DisplayName};
3. Add the legend to the top: Finally, use the "legend" function to add the label to the top. Note that you need to pass the tag's string array as the first argument to the "legend" function.
legend(labels,'Location','northoutside','Orientation','horizontal')
The complete code example is shown below:
% 绘制第一个子图
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')