Search code examples
matlabplotzoomingmatlab-figure

Make "Reset to Original View" zoom out to whole range after using xlim


When you use xlim in MATLAB, the limits you set become the "original view".

This means right clicking with the zoom tool, and selecting "Reset to Original View" doesn't zoom out to the whole range.

For example:

figure(1); 
x = 0:0.1:6
plot( x, sin(x) ); % Example plot, x axis range [0, 6]
xlim( [2, 4] );    % 'Zoom' into the x axis range [2, 4]

plot

% Limits are unchanged at [2, 4] when [0, 6] is desirable.

Now I can pan around, but if I want to zoom out the full range (e.g. [0, 6]) I cannot do so automatically.

I see two possible options, but I can't find a way to implement either:

  1. Instead of using xlim, programmatically zoom into the plot. The zoom function can only take a scale factor input, and doesn't appear useful for zooming to a specific range akin to xlim.

  2. Somehow change the default behaviour of the "Reset to Original View" callback. Not sure I want to hijack this callback, even if I could.

Any ideas?


Solution

  • One option is to use the undocumented command resetplotview.

    From doc resetplotview:

    Internal use only. This function may be removed in a future release.

    Call this function before the xlim command.

    figure(1); 
    x = 0:0.1:6
    plot( x, sin(x) ); % Example plot, x axis range [0, 6]
    resetplotview( gca, 'InitializeCurrentView' ) % Ensure we can reset the zoom
    xlim( [2, 4] );    % 'Zoom' into the x axis range [2, 4]
    

    This has the desired result, where clicking "Reset to Original View" zooms out to the x range [0, 6], but the x range shown initially is [2, 4].


    Because this function is undocumented, it might be useful to have context of the internals. You can edit resetplotview to see where the 'InitializeCurrentView' option is implemented. Essentially it leverages setappdata to define the 'matlab_graphics_resetplotview' attributes, specifically with the XLim property as 'auto'. You could probably do this manually if the resetplotview function was depreciated.