What's the difference of tiledlayout and subplot?

246 次查看(过去 30 天)
The function subplot can already make tiled layout. Why tiledlayout is introduced in 2019b?

采纳的回答

Adam Danz
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.
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 个)

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by