Add individual legends to plots in a tiledlayout
41 ビュー (過去 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!