주요 콘텐츠

New in R2022b: GridSizeChangedFcn
tiledlayout() creates a TiledChartLayout object that defines a gridded layout of axes within a figure. When using the 'flow' option, the grid size becomes dynamic and updates as axes are added or as the figure size changes. These features were introduced in R2019b and if you're still stuck on using subplot, you're missing out on several other great features of tiledlayout.
Starting in MATLAB R2022b you can define a callback function that responds to changes to the grid size in flow arrangements by setting the new gridSizeChangedFcn.
Use case
I often use a global legend to represent data across all axes within a figure. When the figure is tall and narrow, I want the legend to be horizontally oriented at the bottom of the figure but when the figure is short and wide, I prefer a vertically oriented legend on the right of the figure. By using the gridSizeChangedFcn, now I can update the legend location and orientation when the grid size changes.
Demo
gridSizeChangeFcn works like all other graphics callback functions. In this demo, I've named the gridSizeChangedFcn "updateLegendLayout", assigned by an anonymous function. The first input is the TiledChartLayout object and the second input is the event object that indicates the old and new grid sizes. The legend handle is also passed into the function. Since all of the tiles contain the same groups of data, the legend is based on data in the last tile.
As long as the legend is valid, the gridSizeChangedFcn updates the location and orientation of the legend so that when the grid is tall, the legend will be horizontal at the bottom of the figure and when the grid is wide, the legend will be vertical at the right of the figure.
Since the new grid size is available as a property in the TiledChartLayout object, I chose not to use the event argument. This way I can directly call the callback function at the end to update the legend without having to create an event.
Run this example from an m-file. Then change the width or height of the figure to demonstrate the legend adjustments.
% Prepare data
data1 = sort(randn(6))*10;
data2 = sort(randn(6))*10;
labels = ["A","B","C","D","E","F"];
groupLabels = categorical(["Control", "Test"]);
% Generate figure
fig = figure;
tcl = tiledlayout(fig, "flow", TileSpacing="compact", Padding="compact");
nTiles = height(data1);
h = gobjects(1,nTiles);
for i = 1:nTiles
ax = nexttile(tcl);
groupedData = [data1(i,:); data2(i,:)];
h = bar(ax,groupLabels, groupedData, "grouped");
title(ax,"condition " + i)
end
title(tcl,"GridSizeChangedFcn Demo")
ylabel(tcl,"Score")
legh = legend(h, labels);
title(legh,"Factors")
% Define and call the GridSizeChangeFcn
tcl.GridSizeChangedFcn = @(tclObj,event)updateLegendLayout(tclObj,event,legh);
updateLegendLayout(tcl,[],legh);
% Manually resize the vertical and horizontal dimensions of the figure
function updateLegendLayout(tclObj,~,legh)
% Evoked when the TiledChartLayout grid size changes in flow arrangements.
% tclObj - TiledChartLayout object
% event - (unused in this demo) contains old and new grid size
% legh - legend handle
if isgraphics(legh,'legend')
if tclObj.GridSize(1) > tclObj.GridSize(2)
legh.Layout.Tile = "south";
legh.Orientation = "horizontal";
else
legh.Layout.Tile = "east";
legh.Orientation = "vertical";
end
end
end
Give it a shot in MATLAB R2022b
  • Replace the legend with a colorbar to update the location and orientation of the colorbar.
  • Define a GridSizeChangedFcn within the loop so that it is called every time a tile is added.
  • Create a figure with many tiles (~20) and dynamically set a color to each row of axes.
  • Assign xlabels only to the bottom row of tiles and ylabels to only the left column of tiles.
Learn about other new features
This article is attached as a live script.

tiledlayout, introduced in MATLAB R2019b, offers a flexible way to add subplots, or tiles, to a figure.

Reviewing two changes to tiledlayout in MATLAB R2021a

  1. The new TileIndexing property
  2. Changes to TileSpacing and Padding properties

1) TileIndexing

By default, axes within a tiled layout are created from left to right, top to bottom, but sometimes it's better to organize plots column-wise from top to bottom and then left to right. Starting in r2021a, the TileIndexing property of tiledlayout specifies the direction of flow when adding new tiles.

tiledlayout(__,'TileIndexing','rowmajor') creates tiles by row (default).

tiledlayout(__,'TileIndexing','columnmajor') creates tiles by column.

.

2) TileSpacing & Padding changes

Some changes have been made to the spacing properties of tiles created by tiledlayout.

TileSpacing: sets the spacing between tiles.

  • "loose" is the new default and replaces "normal" which is no longer recommended but is still accepted.
  • "tight" replaces "none" and brings the tiles closer together still leaving space for axis ticks and labels.
  • "none" results in tile borders touching, following the true meaning of none.
  • "compact" is unchanged and has slightly more space between tiles than "tight".

Padding: sets the spacing of the figure margins.

  • "loose" is the new default and replaces "normal" which is no longer recommended but is still accepted.
  • "tight" replaces "none" and reduces the figure margins. "none" is no longer recommended but is still accepted.
  • "compact" is unchanged and adds slightly more marginal space than "tight".
  • Reducing the figure margins to a true none is still not an option.

The release notes show a comparison of these properties between r2020b and r2021a.

Here's what the new TileSpacing options (left column of figures below) and Padding options (right column) look like in R2021a. Spacing properties are written in the figure names.

.

And here's a grid of all 12 combinations of the 4 TileSpacing options and 3 Padding options in R2021a.

.

Code used to generate these figures

%% Animate the RowMajor and ColumnMajor indexing with colored tiles 
fig1 = figure('position',[200 200 560 420]); 
tlo1 = tiledlayout(fig1, 3, 3, 'TileIndexing','rowmajor');
title(tlo1, 'RowMajor indexing')
fig2 = figure('position',[760 200 560 420]); 
tlo2 = tiledlayout(fig2, 3, 3, 'TileIndexing','columnmajor');
title(tlo2, 'ColumnMajor indexing')
colors = jet(9);
drawnow()
for i = 1:9
    ax = nexttile(tlo1);
    ax.Color = colors(i,:);
    text(ax, .5, .5, num2str(i), 'Horiz','Cent','Vert','Mid','Fontsize',24)
      ax = nexttile(tlo2);
      ax.Color = colors(i,:);
      text(ax, .5, .5, num2str(i), 'Horiz','Cent','Vert','Mid','Fontsize',24)
      drawnow
      pause(.3)
  end
%% Show TileSpacing options
tileSpacing = ["loose","compact","tight","none"];
figHeight = 140;  % unit: pixels
figPosY = fliplr(50 : figHeight+32 : (figHeight+30)*numel(tileSpacing)); 
for i = 1:numel(tileSpacing)
    uif = uifigure('Units','Pixels','Position', [150 figPosY(i) 580 figHeight], ...
        'Name', ['TileSpacing: ', tileSpacing{i}]);
    tlo = tiledlayout(uif,1,3,'TileSpacing',tileSpacing(i)); 
    h = arrayfun(@(i)nexttile(tlo), 1:tlo.GridSize(2));
    box(h,'on')
    drawnow()
end
%% Show Padding options
padding = ["loose","compact","tight"];
for i = 1:numel(padding)
    uif = uifigure('Units','Pixels','Position', [732 figPosY(i) 580 figHeight], ...
        'Name', ['Padding: ', padding{i}]);
    tlo = tiledlayout(uif,1,3,'Padding',padding(i)); 
    h = arrayfun(@(i)nexttile(tlo), 1:tlo.GridSize(2));
    box(h,'on')
    drawnow()
end
%% Show all combinations of TileSpacing and Padding options
tileSpacing = ["loose","compact","tight","none"];
padding = ["loose","compact","tight"];
[tsIdx, padIdx] = meshgrid(1:numel(tileSpacing), 1:numel(padding));
figSize = [320 220]; % width, height (pixels)
figPosX = 150 + (figSize(1)+2)*(0:numel(tileSpacing)-1); 
figPosY = 50 + (figSize(2)+32)*(0:numel(padding)-1);
[figX, figY] = meshgrid(figPosX, fliplr(figPosY));
for i = 1:numel(padIdx)
    uif = uifigure('Units','pixels','Position',[figX(i), figY(i), figSize], ...
        'name', ['TS: ', tileSpacing{tsIdx(i)}, ', Pad: ', padding{padIdx(i)}]);
    tlo = tiledlayout(uif,2,2,'TileSpacing',tileSpacing(tsIdx(i)),'Padding',padding(padIdx(i))); 
    h = arrayfun(@(i)nexttile(tlo), 1:prod(tlo.GridSize));
    box(h,'on')
    drawnow()
end