I'm trying to individually link both y-axes in an yyaxis subplot. So far I'm only linking the right y-axes in the given code by calling linkaxes(g)
, where g
are the axes handles. How can I also get the left y-axes linked to one another?
Thanks.
g(1) = subplot(2,1,1);
hold on;
yyaxis left;
plot(rand(10,1));
yyaxis right;
plot(2*rand(10,1));
hold off;
g(2) = subplot(2,1,2);
hold on;
yyaxis left;
plot(2*rand(10,1));
yyaxis right;
linkaxes(g);
plot(rand(10,1));
hold off;
An Axes
object has the read-only property YAxisLocation
that is set upon every call to yyaxis
and remembers the last axis that was in use. When you type linkaxes(g)
it simply takes the right axis because that the last one you set. To see that you can run this code for the first axes:
g(1) = subplot(2,1,1);
hold on;
yyaxis right;
plot(2*rand(10,1));
yyaxis left;
plot(rand(10,1));
hold off;
and see how this time the left top axis is linked to the right bottom axis.
If you want to link both axes you just need to add this lines at the end of your code to refer again to the left axis:
yyaxis(g(1),'left')
yyaxis(g(2),'left')
linkaxes(g);
Alternatively, you could grab the handles to the numeric rulers, and use linkprop
(without any call to linkaxes
):
Y = get(g,'YAxis');
Y = [Y{:}];
linkprop(Y(1,:),'Limits')
linkprop(Y(2,:),'Limits')
You should add this after all axis are created, so all the handles will be assigned already.