xline for multiple axes in tiled layout

How can I use xline or yline to make line in multiple axes of a tiled layout without having to write the lines for every tile?
I have the following code to plot multiple data in a tiled layout.
t = tiledlayout(1,2);
t1 = nexttile;
semilogy(x1,y1); hold on;
semilogy(x2,y2);
legend('x1','y1');
title('Data 1')
xline(3,'-')
xline(5,'-')
t2 = nexttile;
semilogy(xx1,yy1); hold on;
semilogy(xx2,yy2);
legend('xx1','xx2');
title('Data 2')
xline(3,'-')
xline(5,'-')
linkaxes([t1 t2],'x');
t1.XLim = [0 300];
While linkaxes works to set the limits, I am not sure how I can do this for the xline or yline functions.

 Accepted Answer

The ‘ax’ argument to xline has to be a scalar axes handle, so passing a vector of axes handles to it fails. Each nexttile call creates a new axes, so subscript them and then use arrayfun, or a for loop —
t = tiledlayout(1,2);
tl(1) = nexttile;
plot(1:50, randn(1,50))
tl(2) = nexttile;
plot(1:40, randn(1,40))
arrayfun(@(ax)xline(ax,[3 5], 'r', 'LineWidth',2), tl)
.

4 Comments

This is great, thanks. I have one follow up question. Can I assign different properties value to different lines? I can do that with labels by having them in a cell as below
t = tiledlayout(1,2);
tl(1) = nexttile;
xline(tl(1),[3 5],'-',{'L1','L2'})
xlim([0 7])
But the same would not apply if I am to do that with ,for example, the vertial alignment of labels:
xline(tl(1),[3 5],'-',{'L1','L2'},'LabelVerticalAlignment',{'bottom', 'top'})
would not work.
I could do it with individual assignment to objects like the following:
t = tiledlayout(1,2);
tl(1) = nexttile;
xl= xline(tl(1),[3 5],'-',{'L1','L2'})
xl(1).LabelVerticalAlignment = "top";
xl(2).LabelVerticalAlignment = "bottom";
xlim([0 7])
But is it possible to do it in the xline function line itself?
But is it possible to do it in the xline function line itself?’
Yes, however the 'LabelVerticalAlignment' cell array has to be created outiside the arrayfun call because it is necessary to index into it —
t = tiledlayout(1,2);
tl(1) = nexttile;
plot(1:20, randn(1,20))
tl(2) = nexttile;
plot(1:15, randn(1,15))
LVA = {'bottom', 'top'}; % 'LabelVerticalAlignment' Cell Array
arrayfun(@(k)xline(tl(k),[3 5], 'r', {'L1','L2'},'LabelVerticalAlignment',LVA{k}), 1:numel(tl))
That may also be true for other properties. If so, this example provides an approach to that.
NOTE — The arrayfun call changed slightly from the earlier version in order to provide a way to index into the ‘LVA’ cell array and still work as originally desired.
.
Makes it clear. Thanks a lot!
As always, my pleasure!

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2022b

Community Treasure Hunt

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

Start Hunting!