Add second x axis at the bottom of each subplot

I'd like to have two x-axis for each subplot.
The number of subplots is not always 2. (max. 5)
My code:
t = 0:10;
y = {sin(t);cos(t)};
j = 1;
for i = 1:2
time_plot = figure(2);
ax(j) = subplot( 2, 1, j);
plot( t, y{i} );
xlim([0 10]);
xlabel('t (s)');
ylabel('f(t)');
j = j + 1;
hold on;
end
The current result looks like this:
But it should look like this:
EDIT:
My first approach is this:
t = 0:10;
y = {sin(t);cos(t)};
%y = {sin(t);cos(t);t.*t};
j = 1;
xTicks = 0:10;
for i = 1:length(y)
time_plot = figure(2);
ax(j) = subplot( length(y), 1, j);
p = plot(t, y{i});
if length(y) < 3
hAx1=gca; % get the first axis handle so can address each desired
pos = get(hAx1, 'position');
hAx2=axes('YAxisLocation','right', ...
'Color','none', ...
'YTick',[]);
%{
hAx2=axes('YAxisLocation','right', ...
'Color','none', ...
'YTick',[], 'XTick', xTicks);
%}
hAx2.Position = hAx1.Position-[0 0.055 0 0];
hAx2.YAxis.Visible = 'off';
hAx2.Interactions = [dataTipInteraction];
xlim(hAx1, [0 10]);
xlim(hAx2, [0 5]);
xlabel(hAx1, 't (s)');
xlabel(hAx2, 't2 (s)');
ylabel(hAx1, 'f(t)');
else
xlim([0 10]);
xlabel('t (s)');
ylabel('f(t)');
end
j = j + 1;
%linkaxes([hAx1, hAx2] , 'x');
hold on;
end
This gives us the following result:
What I'd like to achieve now is to enable zoom for both axes. How does this work?

7 Comments

Mind boggling there isn't yet a parallel universe to yyaxis supplied. I do believe there are submissions on FEX altho I don't have a direct link. Otherwise, you must build it yourself; the basic code to see how is available to see in the plotyy that adds the second y-axis m-file although here you'll have to shorten height and raise the bottom of the x axis to make room for the second.
But the axes should keep their limits. (5 and 10)
If I use 'linkaxes' then both axes will have the same limits (0 and 10)
Well, zoom will only allow all axes in a figure; you've got four axes above. If all of them are OK to move at once, that may work (I've never messed with it).
Otherwise, think you'd have to have callbacks of your own to do the work.
Yes, it is okay to move all of them at once. But how can I do this without losing the limits?
How can I add a legend to each subplot?
Either add it at the same time as add the data to each subplot so it is still the current (the one whos handle is returned by gca) axes or be sure to save all the axes handles when you create them and use the specific handle to each in turn when call <as documented in legend>.

Sign in to comment.

Answers (0)

Categories

Asked:

on 25 May 2022

Commented:

dpb
on 8 Sep 2022

Community Treasure Hunt

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

Start Hunting!