Add individual legends to plots in a tiledlayout
38 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam Danz
2024-5-17
编辑:Adam Danz
2024-5-17
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 个评论
更多回答(1 个)
Mathieu NOE
2024-5-17
移动:Mathieu NOE
2024-5-17
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!