Axes auto-zoom based on a given line

31 views (last 30 days)
In an application, I plot one series of data and a number of vertical lines showing where certain "events" occur along the data plot. The vertical lines' y-values are [min(data), max(data)]. I constrain the plot to x-zoom for a scrolling effect.
The drawback to this setup is this: If there is a single spike anywhere in the data, the vertical lines extend to its peak (max(data)). Thus the plot's YLim range is now very large, so other data trends get "flattened out". The user has asked if the y-zoom can be set to "auto", so he can see these other data trends when he x-zooms in another area (so it doesn't include the spike). But alas, y-zoom(auto) has no effect, because the vertical event lines have a height equal to the full data range.
So my question is: Can y-zoom be set to rescale based on one data series in the plot, instead of all of them?
Thanks in advance.

Accepted Answer

Cam Salzberger
Cam Salzberger on 31 Aug 2015
Hello,
I understand that you would like to be able to constrain the zoom in the y-dimension based on what data if currently in view. Probably the easiest way would be to create a callback for the zoom object that manually adjusts the y-limits based on the data. This documentation page is helpful in determining the format of the callback functions, and other zoom properties.
Here is a quick example to demonstrate how to do exactly that:
function ZoomCallbackExample
% Sample data
x = 1:100;
y = rand(size(x));
y(5) = 5;
xEvents = 10:10:90;
yMin = min(y);
yMax = max(y);
% Plot data and events
hFig = figure;
plot(x,y,'-k')
hold on
for iEvent = 1:numel(xEvents)
plot([xEvents(iEvent) xEvents(iEvent)],[yMin yMax],'-r')
end
hold off
% Modify zoom behavior
hZoom = zoom(hFig);
hZoom.Motion = 'horizontal'; % Only allow user to zoom x-axis
hZoom.ActionPostCallback = @(obj,objEvent) afterZoom(obj,objEvent,x,y);
end
function afterZoom(~,objEvent,x,y)
% Change axes y-limits to match only what data is shown
hAx = objEvent.Axes;
yInView = y(x >= hAx.XLim(1) & x <= hAx.XLim(2));
hAx.YLim = [min(yInView) max(yInView)];
end
I hope this demonstrates the effect you are trying to achieve.
-Cam
  2 Comments
CAM
CAM on 1 Sep 2015
Thank you so much! This is exactly what I needed. I also set up the Pan feature to call afterZoom as well.
Cam Salzberger
Cam Salzberger on 1 Sep 2015
Glad you caught that; I forgot to mention adding the Pan callback. Thanks for the reminder.
As a side note, you can add a handler for rotation in 3-D as well, although you don't need that for this application.

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!