100 views (last 30 days)
Jason on 24 Nov 2014
I am plotting for subplots (2,2,i) on a figure and want all the Y'axis to be the same. As I'm plotting them sequentially, I will only know all the max Y values once all 4 are plotted.
Can I go back, work out the max Y limit and then reapply that to the other plots?
Thanks Jason

Thorsten on 24 Nov 2014
Do your plots and store the gca for each plot
for i = 1:3
subplot(1, 3, i)
plot(10*hist(rand(1, 100))); % some random data
mygca(i) = gca;
end
Get the ylimits of each subplot
yl = cell2mat(get(mygca, 'Ylim'))
Compute new limits for each subplot
ylnew = [min(yl(:,1)) max(yl(:,2))];
set(mygca, 'Ylim', ylnew)
The nice thing is that you can use 'set' with a vector of gca's as argument.
Thorsten on 26 Nov 2014
Well, that's a different question!

'Yes'
would be the answer to your question. I assume you are asking how to do it though? There are numerous ways.
You could keep track of the maxima of your data as you plot it and then just set the 'YLim' property of all of the axes appropriately, you can plot them all, then get the 'YLim' property from them all, find the largest and apply that to them all or variations on the same theme, assuming you keep track of your axes handles.
You are setting each one to the same thing that it already was by using num2str( get( mygca, 'YTick' ) ).
You need to get the ticks from the one that is correct and create labels from that and then set those across all, or just for each axes do whatever you did in the first place to change the notation from exponential every time you change y limits.
There is a 'PostSet' event that you can add a listener to I think, though I have never used it on graphics objects, only my own objects.
I think though you can do something like:
addlistener( hAxes, 'XLim', 'PostSet', callback )
You may be better using linkprop after all on the 'YTick' and 'YTickLabel' properties. Link all your axes together and then just update the YTick and YTickLabel of the first axes and the rest will follow.

Adam Danz on 15 Apr 2021 at 15:55
Another approach is to use linkaxes to link the y-axis limits of all subplots. When combined with axis tight, that y-axis range of all subplots will equal the largest range of data in all plots.
clf()
ax = gobjects(9,1);
for i = 1:9
ax(i) = subplot(3,3,i);
plot(randi(randi(1000),1,20), 'o');
axis(ax(i),'tight')
end

Community Treasure Hunt

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

Start Hunting!