MATLAB: Zoom ‘auto’ doesn’t work with linkaxes when data is replaced

clickdatadoublelinkaxesMATLABrangezoom

I plot two subplots in my figure. After changing the data of the plots, the behavior of a 'doubleclick' in zoom mode doesn't work well anymore. It fits the axes limits to the OLD data instead of the new data. This problem appears only when the axes are linked.
x1 = 0:5;
y = rand(size(x1));
y2 = rand(size(x1));
ax1 = subplot(2,1,1)
myPlt1 = plot(x1, y);
ax2 = subplot(2,1,2)
myPlt2 = plot(x1, y2);
linkaxes([ax1 ax2], 'x');
waitfor(warndlg('Now zoom a bit in one of the two axes'))
x2 = x1/2;
myPlt1.XData = x2
myPlt2.XData = x2
warndlg('doubleclick on axes will cause x axes zoom to 0-5 instead of 0-2.5')

Best Answer

When you call linkaxes, it sets the XLimMode and YLimMode to 'manual' on each of the axes. Without it, they are set to 'auto'.
When you zoom for the first time, it stores the XLim and YLim values and resets to those values when you reset except if XLimMode and YLimMode (or any mode property related to a property that interactions set) is auto, in which case it sets the XLimMode and YLimMode back to 'auto'.
In this case, the zoom is going back to the stored (original) XLim and Ylim values (0-5 for XLim), instead of going back to the 'auto' position for the data.
In order to have the behavior go back to the 'auto' position for linkedaxes, use one of these two methods:
1. Set the XLimMode and YLimMode back to 'auto' after executed linkaxes:
>> ax1.XLimMode='auto'
2. Execute zoom reset whenever the data is switched. This will set the home limits to the current limits (or to 'auto' if they are in 'auto'):
>> zoom reset