I am generating a plot in real-time. I shift the x-axis by 30 seconds, every 30 seconds. This is all well and good, but my y-axis is auto-resizing itself to smaller than previously. Take a look below:
This is my data before we hit the 30 seconds and redraw the x-axis labels. I'm just plotting ±cos(t)
right now, so my Y limits are [-1 1].
After the 30 seconds, I shift the axes over to start watching the plot generate on the time interval [30 60]. Notice that my Y limits have rescaled to [-0.8 0.5]. As time increases, the limits go back to [-1 1]. But I would like to have continuity between the previous 30 second snapshot and the current snapshot in time, i.e., limits should be [-1 1] immediately after hit the 30 second threshold.
Is there a way to keep the previous Y limits and still let them grow properly (i.e., if Y data goes over limits it'll resize appropriately, automatically)?
The y-axis limits will rescale automatically if the YLimMode
of the axis is set to auto
. Set it to manual
to prevent this:
>> set(gca, 'YLimMode', 'manual');
In order to have the limits update automatically to appropriate values when the data on the plot is updated you could listen for updates to the line using an event listener. This approach requires you to update the plotted line by updating the line's XData
and YData
properties. Create the line and listener:
>> h = line('XData', [], 'YData', []); >> addlistener(h, 'YData', 'PostSet', @(src, evnt) set(evnt.AffectedObject.Parent, 'YLim', [min(evnt.AffectedObject.YData) max(evnt.AffectedObject.YData)]));
The listener definition includes an anonymous function that uses the event properties to access the line's parent (i.e. the axes) and set the y-axis limits to the minimum and maximum of the plotted y values. This function is executed when the YData
property of the plotted line is updated.
To see this in action, try the following:
>> x = 1; >> y = cos(x); >> for ii = 2:1000 x(end+1) = ii; y(end+1) = cosd(x(end)); set(h, 'XData', x, 'YData', y); pause(0.01); end