Add individual legends to plots in a tiledlayout
39 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Daniel
el 17 de Mayo de 2024
Comentada: Mathieu NOE
el 21 de Mayo de 2024
Hi,
I would like to create a tiled layout with both a tile-specific and a common legend.
The tile-specific legend should contain a reference to the data contained only on the tile, whereas the common legend should refer to data across all tiles.
Here is a simple code to illustrate what I'm trying to do. The tile legends should refer to the yline and the common legend at the bottom should refer to data in all plots. Hopefully this makes sense.
Can anybody help?
Thank you
x = linspace(0,30);
y1 = sin(x);
y2 = sin(x);
figure
tiledlayout(1,2)
ax1 = nexttile(1);
plot(x,y1)
yline(0,'--')
legend(ax1, '', 'y=0')
ax2 = nexttile(2);
plot(x,y2)
yline(0.5,'--')
legend(ax2, '', 'y=0.5')
leg = legend('sin(x)');
leg.Layout.Tile = 'south';
0 comentarios
Respuesta aceptada
Adam Danz
el 17 de Mayo de 2024
Editada: Adam Danz
el 17 de Mayo de 2024
Only one legend can be assigned to an axes. This poses a problem if each axes has a legend and you want to add a global legend because there are no axes left to assign it to.
The solution is to create an invisible axes that is parented to the TiledChartLayout object. Then you can assign the global legend to that axes and specify the legend location using the tiled layout.
hiddenAxes = axes(tcl,'visible','off');
The second tip is the use the DisplayName property to assign legend strings to objects and then use the object handles to specify which objects go in which legend.
tcl = tiledlayout(1,2);
ax(1) = nexttile(tcl);
hold on
h = plot(sin(0:.3:12),'DisplayName','data1');
c = plot(abs(sin(0:.3:12)),'DisplayName','data2');
yl(1) = yline(0,'--','DisplayName','y=0');
% Apply legend to tile 1
legend(ax(1),yl(1))
ax(2) = nexttile(tcl);
hold on
plot(sin(0:.3:12),'DisplayName','data1');
plot(abs(sin(0:.3:12)),'DisplayName','data2');
yl(2) = yline(0.3,'--','DisplayName','y=0.3');
% Apply legend to tile 2
legend(ax(2),yl(2))
% Apply global legend
hiddenAxes = axes(tcl,'visible','off');
gleg = legend(hiddenAxes,[h,c]);
gleg.Layout.Tile = 'South';
gleg.Orientation = 'horizontal';
2 comentarios
Más respuestas (1)
Mathieu NOE
el 17 de Mayo de 2024
Movida: Mathieu NOE
el 17 de Mayo de 2024
my 2 cents suggestion
x = linspace(0,30);
y1 = sin(x);
y2 = sin(x);
figure
t = tiledlayout(1,2);
ax1 = nexttile(1);
plot(x,y1)
yline(0,'--')
legend(ax1, '', 'y=0')
ax2 = nexttile(2);
plot(x,y2)
yline(0.5,'--')
legend(ax2, '', 'y=0.5')
% title(t,'Sin(x)') % to have it on top
xlabel(t,'Sin(x)') % to have it on the bottom side
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!