1

Following is the code I've written which involves a subplot command inside a for loop. I want each subplot to have the same y-axis limits, say 0 to 15. But the three plots have different (adjusted) y-axis limits which defeats the very purpose of comparing the three plots. How do I maintain same ylimits in all three subplots?

w = -pi:0.001:pi;
N = [8 10 14];

for i = 1:3
    subplot(3, 1, i);
    W = exp(-1i*w*(N(i)-1)/2).*sin(w*N(i)/2)./sin(w/2);
    plot(w, abs(W));
    xlabel('\omega'); ylabel('Magnitude');
    title(sprintf('N = %d', N(i)));
end
MaxFrost
  • 217
  • 1
  • 6

1 Answers1

0

You can use linkaxes for that:

w = -pi:0.001:pi;
N = [8 10 14];

ax = NaN(1,3); % preallocate
for i = 1:3
    subplot(3, 1, i);
    ax(i) = gca; % take note of axis handle
    W = exp(-1i*w*(N(i)-1)/2).*sin(w*N(i)/2)./sin(w/2);
    plot(w, abs(W));
    xlabel('\omega'); ylabel('Magnitude');
    title(sprintf('N = %d', N(i)));
end
linkaxes(ax) % link axis limits

As an alternative, you can set the axis limits manually to the maximum size required by all subplots:

w = -pi:0.001:pi;
N = [8 10 14];

ax_size = NaN(3,4); % preallocate
for i = 1:3
    subplot(3, 1, i);
    W = exp(-1i*w*(N(i)-1)/2).*sin(w*N(i)/2)./sin(w/2);
    plot(w, abs(W));
    ax_size(i,:) = axis; % take note of axis size
    xlabel('\omega'); ylabel('Magnitude');
    title(sprintf('N = %d', N(i)));
end
ax_target = [min(ax_size(:,1),[],1) max(ax_size(:,2),[],1) ...
     min(ax_size(:,3),[],1) max(ax_size(:,4),[],1)]; % compute target size
for ii = 1:3
    subplot(3, 1, ii);
    axis(ax_target) % set target size
end
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Ok, so I made the same edit to my code and ran it. It happens that the maximum value of the y-axis ends well below the maximum value of one of the subplots, causing it to cutoff small portion of the graph. How do I make sure all the subplots are accommodated properly well within the respective subplot figures? – MaxFrost Oct 29 '18 at 12:40
  • @MaxFrost I0m not sure what you mean. In the example in my code (taken from yours) the y-axis limits were originally 10, 10, 20, and with `linkaxes` they become 20, 20, 20. Is that not what you want? – Luis Mendo Oct 29 '18 at 12:43
  • They remain at 10, 10, 10 in my case. Any idea why this difference? I copy-pasted the code from your answer and I still end up with 10, 10, 10. – MaxFrost Oct 29 '18 at 13:55
  • @MaxFrost Perhaps the behaviour is version-dependent. I'm using R2017b. You may need to set the axis size manually to the max and min of the individual subplots; see second part of edited answer – Luis Mendo Oct 29 '18 at 14:47