Reputation: 704
I create a a simple timeseries plot. Then I zoom in. When I zoom in, I'd like to calculate the mean of the zoomed areas Y data, and plot it on the same figure with the original Y data. I have tried the following code, but what it does it erase the original Y data, and only plots the mean data.
d = rand(1,length(t));
f = figure;ta = plot(t,d)
he = zoom;
guidata(ta,struct('d',d't',t,'axes',ta));
he.ActionPostCallback = @calcMean;
function calcMean(obj,evd)
data = guidata(obj);
newLim = evd.Axes.XLim;
tStart = round(newLim(1));
tEnd = round(newLim(2));
Croppedt = find(data.t(tStart:tEnd));
CroppedD = ones(1,length(Croppedt)).*mean(data.d(Croppedt));
plot(gca,data.t(tStart:tEnd),CroppedD,'r')
end
Any ideas? Thanks!
Upvotes: 0
Views: 153
Reputation: 5672
You need to hold
the plot to stop it erasing the original data.
Put the following code after you create the 1st plot.
hold on
Ideally you should tell hold which axes to hold:
f = figure;
ax = axes ( 'parent', f );
plot ( ax, .... )
hold ( ax, 'on' )
While not strictly necessary (Matlab will assume gca
is the current axes if not specified - it is good practice and likely to avoid some bugs in the future if you write more complex code etc...
edit You need to save the handle to the zoomed plot, something like (untested)
function calcMean(obj,evd)
data = guidata(obj);
newLim = evd.Axes.XLim;
tStart = round(newLim(1));
tEnd = round(newLim(2));
Croppedt = find(data.t(tStart:tEnd));
CroppedD = ones(1,length(Croppedt)).*mean(data.d(Croppedt));
if isfield ( data, 'zoomHandle' )
delete ( data.zoomHandle )
end
data.zoomHandle = plot(gca,data.t(tStart:tEnd),CroppedD,'r');
% you then need to update the guidata to save the handle.
guidata(obj,data);
end
Upvotes: 1