How to create an overall legend that includes all appeared data groups?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Zhe Dong
el 1 de Ag. de 2024
Comentada: Zhe Dong
el 1 de Ag. de 2024
I'm trying to make a plot, using the tiledlayout function to create 4 subplots, while in the first subplot, there are 5 data groups, while the remaining subplots only have four of those 5 groups. If I create an overall legend, it will only show 4 groups that appeared in all the subplots, and automatically omit the extra one that's only shown in the first subplot, how to include that grounp into the overall legend as well? Thanks!
0 comentarios
Respuesta aceptada
Avni Agrawal
el 1 de Ag. de 2024
I understand that you are trying too create an overall legend in MATLAB that includes all data groups from multiple subplots, you can manually specify the legend entries by using the legend function with the appropriate handles.
Here is an example using the tiledlayout function:
% Create a tiled layout
t = tiledlayout(2, 2);
% Generate some example data
x = linspace(0, 10, 100);
y1 = sin(x);
y2 = cos(x);
y3 = tan(x);
y4 = sin(x) .* cos(x);
y5 = sin(x) .^ 2;
% First subplot with 5 data groups
nexttile;
h1 = plot(x, y1, 'r'); hold on;
h2 = plot(x, y2, 'g');
h3 = plot(x, y3, 'b');
h4 = plot(x, y4, 'k');
h5 = plot(x, y5, 'm');
title('Subplot 1');
hold off;
% Second subplot with 4 data groups
nexttile;
plot(x, y1, 'r'); hold on;
plot(x, y2, 'g');
plot(x, y3, 'b');
plot(x, y4, 'k');
title('Subplot 2');
hold off;
% Third subplot with 4 data groups
nexttile;
plot(x, y1, 'r'); hold on;
plot(x, y2, 'g');
plot(x, y3, 'b');
plot(x, y4, 'k');
title('Subplot 3');
hold off;
% Fourth subplot with 4 data groups
nexttile;
plot(x, y1, 'r'); hold on;
plot(x, y2, 'g');
plot(x, y3, 'b');
plot(x, y4, 'k');
title('Subplot 4');
hold off;
% Create an overall legend
lgd = legend([h1, h2, h3, h4, h5], {'Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'});
lgd.Layout.Tile = 'north'; % Place the legend at the top of the tiled layout
% Set the renderer to 'painters' or 'opengl'
set(gcf, 'Renderer', 'painters'); % You can also try 'opengl'
I hope this helps!
Más respuestas (0)
Ver también
Categorías
Más información sobre Legend en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!