Issue with linkprop outcome in .m vs .mlx script

I want to create a four plot figure and link the axes in the following configuration:
  • y-axis on the upper left plot and upper right plot
  • y-axis on the lower left plot ant lower right plot
  • x-axis on both left and right, upper and lower plot
I was able to accomplish this with the linkprop function and 'XLim' and 'YLim' properties in a .m script. However using this method in a .mlx script does not link any of the axes. When comparing the properties listed in each, it appears that there are additional properites in the .mlx, but none seem responsible for this not working. Below is a sample code that should illustrate the issue im discribing, it will link the axes properly in a .m, but have no effect in a .mlx. Ultimately I would like to establish a way to complete this in a .mlx script.
x = linspace(0,10);
y1 = sin(x);
y2 = cos(x);
y3 = 2*sin(x);
y4 = 2*cos(x);
figure()
fig = tiledlayout(2,2);
ax(1) = nexttile;
plot(x,y1)
ax(2) = nexttile;
plot(x,y2)
ax(3) = nexttile;
plot(x,y3)
ax(4) = nexttile;
plot(x,y4)
link{1} = linkprop([ax(1) ax(2)], 'YLim');
% Linking y-axis on upper left and upper right
link{2} = linkprop([ax(3) ax(4)],'YLim');
% Linking y-axis on lower left and lower right
link{3} = linkprop(ax, 'XLim');
% Linking x-axis on all plots %

 Accepted Answer

The problem is that the embedded figure within the live scrip does not have access to the LinkProp objects. The documentation hints at this "the link object must exist within the context where you want property linking to occur".
You can achieve this by storing the LinkProps to the figure. Here are two solutions. It's a good idea to follow this habit any time you're using linkprop.
Option 1: Store LinkProp in the figure's UserData
fig = figure();
% ...
fig.UserData.link{1} = linkprop([ax(1) ax(2)], 'YLim');
fig.UserData.link{2} = linkprop([ax(3) ax(4)],'YLim');
fig.UserData.link{3} = linkprop(ax, 'XLim');
Option 2: Store LinkProp in the figure using setappdata
fig = figure();
% ...
link{1} = linkprop([ax(1) ax(2)], 'YLim');
link{2} = linkprop([ax(3) ax(4)],'YLim');
link{3} = linkprop(ax, 'XLim');
setappdata(fig,'LinkProp',link)

More Answers (0)

Products

Release

R2023a

Asked:

on 23 Jun 2023

Edited:

on 23 Jun 2023

Community Treasure Hunt

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

Start Hunting!