MATLAB Zoom 然后绘制新数据

MATLAB Zoom then plot new data

我创建了一个简单的时间序列图。然后我放大。当我放大时,我想计算缩放区域 Y 数据的平均值,并将其绘制在与原始 Y 数据相同的图形上。我试过下面的代码,但它会擦除原始 Y 数据,只绘制平均数据。

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

有什么想法吗?谢谢!

您需要hold 绘图以阻止它擦除原始数据。

在创建第一个图后输入以下代码。

hold on

理想情况下,你应该告诉 hold 要保持哪个轴:

f = figure;
ax = axes ( 'parent', f );
plot ( ax, .... )
hold ( ax, 'on' )

虽然不是绝对必要的(如果未指定,Matlab 将假设 gca 是当前轴 - 这是一种很好的做法,如果您编写更复杂的代码等,将来可能会避免一些错误...

编辑 您需要将句柄保存到缩放图,例如 (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);

结束