What's the difference of tiledlayout and subplot?
236 次查看(过去 30 天)
显示 更早的评论
The function subplot can already make tiled layout. Why tiledlayout is introduced in 2019b?
1 个评论
采纳的回答
Adam Danz
2021-6-6
编辑:Adam Danz
2021-6-8
tiledlayout has additional features not supported in subplot. Changing subplot would cause backward compatibility issues.
- Sean de Wolski's September 2019 blog post reviews some limitations to subplot and some new features available in tiledlayout.
- MathWorks posted a thread in reddit highlighting a tiledlayout feature that lets you add tiles without defining a layout matrix using the flow feature.
- A recent community highlight shows some tiledlayout spacing options that are not supported with subplot.
- Global legend, global titles, and global axis labels that span the entire grid of axes are easy to do with tiledlayout.
Demo
Two blocks below produce nearly the same figure using tiledlayout and subplot while using as few lines as possible without sacrificing best-practices.
A subplot/tile will be added for each column of x but the number of columns of data are unknown!
Produce data
rng(210606) % for reproducibility of this dataset
n = randi([4,9]); % number of subplots/tiles needed
x = randn(200,n) .* (1./10.^[0:n-1]);
tiledlayout
fig = figure();
tlo = tiledlayout(fig, 'flow');
arrayfun(@(col)histogram(nexttile(tlo),x(:,col)),1:n); % *see below
title(tlo,'Global title')
ylabel(tlo, 'Global ylabel')
xlabel(tlo, 'Global xlabel')
The arrayfun line is the same as this loop:
for i = 1:n
ax = nexttile(tlo);
histogram(ax, x(:,i));
end
subplot
The label placement took a long time to figure out relative to the tiledlayout example.
fig = figure();
nRows = ceil(sqrt(n)); % compute number of subplot rows
nCols = ceil(n/nRows); % compute number of subplot columns
arrayfun(@(col)histogram(subplot(nRows,nCols,col),x(:,col)),1:n); % *see below
sgtitle('Global title')
annotation(fig,'textarrow',[.15 .15], [.52 .52], ... % <-- estimated margin
'String','Global ylabel',...
'TextRotation',90,...
'FontSize',12,...
'HorizontalAlignment','Center',...
'VerticalAlignment','Middle',...
'HeadStyle','none',...
'LineStyle','none',...
'TextMargin', .1);
annotation(fig,'textarrow',[.6 .6], [.03 .03], ... % <-- estimated margin
'String','Global xlabel',...
'FontSize',12,...
'HorizontalAlignment','Center',...
'VerticalAlignment','Middle',...
'HeadStyle','none',...
'LineStyle','none',...
'TextMargin', .1);
The arrayfun line is the same as this loop:
for i = 1:n
ax = subplot(nRows,nCols,i);
histogram(ax, x(:,i));
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Subplots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!