0
Follow
0
View

matlab drawing, legend only follows the last drawing

dajinnan 注册会员
2023-02-25 19:12

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')


About the Author

Question Info

Publish Time
2023-02-25 19:11
Update Time
2023-02-25 19:11

Related Question

关于#matlab#的问题:matlab有a和b两个版本这两个版本都有什么区别

matlab-simulink关于device模块使用

C#调用matlab出现“MWNumericArray的类型初始值设定项引发异常”错误,求解!!。

matlab中代码详细解释注释一下

VS2022的python环境有没有类似Matlab和Spyder的变量浏览器呀

如何将带有字符串和空行的csv文件导入到matlab中

用matlab画图,可议价,这周周末之前要

matlab隐函数求解问题

matlab里如何调用function

matlab代码出错