Clear Filters
Clear Filters

How to make uigridlayout adjust spacing as tiledlayout?

13 views (last 30 days)
I'm using uigridlayout, and I need it to adjust spacing in the same way as it is done automatically by tiledlayout. The reason I am using uigridlayout, instead of tiledlayout, is that I'm working with an uifigure (instead of a regular figure), and I need that, since uifigure can be made scrollable, while figure cannot.
When legends of arbitrary lengths are placed east-outside of a plot, tiledlayout automatically re-adjusts the spacing of all "tiles" (grid cells), aligning the axes. This is not so with uigridlayout (see attached image). Solution to this problem should be based on the MWE provided below.
First part:
%MWE
all_fig = findall(0, 'type', 'figure');
close(all_fig);
clear;
clc;
%Parameters
N = 8;
layout = [N 1];
%Pre-alloc
DataCell = cell(N,1);
x = 0:0.1:10;
L_x = length(x);
DataMatrix = zeros(L_x, 2);
for n=1:N
DataMatrix(:,1) = x;
DataMatrix(:,2) = n*rand([L_x, 1]);
DataCell{n} = DataMatrix;
end
%GRAPHICS
mwe_plot(DataCell, layout);
and second part:
%MWE: PLOT
function mwe_plot(DataCell, layout)
%Extract
Rows = layout(1);
Cols = layout(2);
%Variable for legend string
s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
%Figure
fig = uifigure('Name', 'MWE', 'WindowState', 'maximized', 'Scrollable', 'on', 'HandleVisibility', 'on');
UIgrid = uigridlayout(layout,'Parent',fig);
n = 1;
for col=1:Cols
for row=1:Rows
%Extract Data
DataMatrix = DataCell{n};
x = DataMatrix(:,1);
y = DataMatrix(:,2);
%Axes
ax = uiaxes(UIgrid);
ax.Layout.Row = row;
ax.Layout.Column = col;
%Plot
plot(ax, x, y);
grid(ax,'on');
box(ax,'on');
%Legend
legend_string = s(1:min(2*n,length(s)));
legend(ax, legend_string,'Location', 'eastoutside');
%Update n
n = n + 1;
end
end
end

Accepted Answer

Luca Carlino
Luca Carlino on 1 Mar 2024
There appears to be no practical solution to this problem. For some reason, when legend is placed outside, the InnerPosition property of uiaxes includes the space taken by the legend itself (instead of the strict plot-box, labels excluded). Thus, one cannot manipulate the plot-box dimensions independently of the legend. As far as I can tell, this is a MATLAB limitation.
P.S. As a work-around, one can place the text in the legend as a title, and then fix the axes dimensions (Position property). Clearly, this only works if you have a single Line in a plot (or, to be more precise, a single Line for which you actually care of having a legend associated with it), but since this was my case, it is a fine work-around.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!