MATLAB - How to zoom subplots together?

MatlabPlotZooming

Matlab Problem Overview


I have multiple subplots in one figure. The X axis of each plot is the same variable (time). The Y axis on each plot is different (both in what it represents and the magnitude of the data).

I would like a way to zoom in on the time scale on all plots simultaneously. Ideally by using the rectangle zoom tool on one of the plots, and having the other plots change their X limits accordingly. The Y limits should remained unchanged for all of this. Auto fitting the data to fill the plot in the Y direction is acceptable.

(This question is almost identical to Stack Overflow question one Matplotlib/Pyplot: How to zoom subplots together? (except for MATLAB))

Matlab Solutions


Solution 1 - Matlab

Use the built-in linkaxes function as follows:

linkaxes([hAxes1,hAxes2,hAxes3], 'x');

For more advanced linking (not just the x or y axes), use the built-in linkprop function

Solution 2 - Matlab

Use linkaxes as Yair and Amro already suggested. Following is a quick example for your case

ha(1) = subplot(2,1,1); % get the axes handle when you create the subplot
plot([1:10]);           % Plot random stuff here as an example
ha(2) = subplot(2,1,2); % get the axes handle when you create the subplot
plot([1:10]+10);        % Plot random stuff here as an example

linkaxes(ha, 'x');      % Link all axes in x

You should be able to zoom in all the subplots simultaneously

If there are many subplots, and collecting their axes handle one by one does not seem a clever way to do the job, you can find all the axes handle in the given figure handle by the following commands

figure_handle = figure;
subplot(2,1,1); 
plot([1:10]);   
subplot(2,1,2); 
plot([1:10]+10);

% find all axes handle of type 'axes' and empty tag
all_ha = findobj( figure_handle, 'type', 'axes', 'tag', '' );
linkaxes( all_ha, 'x' );

The first line finds all the objects under figure_handle of type "axes" and empty tag (''). The condition of the empty tag is to exclude the axe handles of legends, whose tag will be legend.

There might be other axes objects in your figure if it's more than just a simple plot. In such case, you need to add more conditions to identify the axes handles of the plots you are interested in.

Solution 3 - Matlab

To link a pair of figures with linkaxes use:

figure;imagesc(data1);
f1h=findobj(gcf,,’type’,’axes’)
figure;imagesc(data2);
f2h=findobj(gcf,,’type’,’axes’)
linkaxes([f1h,f2h],’xy’)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiebsterView Question on Stackoverflow
Solution 1 - MatlabYair AltmanView Answer on Stackoverflow
Solution 2 - MatlabYYCView Answer on Stackoverflow
Solution 3 - MatlabrazaporView Answer on Stackoverflow