MATLAB: Animatedline fails after the first iteration

addpointsanimatedlineline animationloopMATLAB

Hi,
It was previously working but now I am getting an empty plot in the second subplot after the first iteration. Code is as follows:
for i=1:10:length(tu)
ax1= subplot(2,1,1)
pcolor(lontemp(findnearest(150,lontemp):findnearest(160, lontemp)),lattemp, hc')
Y1=get(gca,'ylim');
set(ax1,'dataaspectratio',[.7 cos((Y1(2)+Y1(1))/5/180*pi) 1], 'position',[0.204,0.5,0.55,0.42])
ax2=subplot(2,1,2)
if i==1
curve1=animatedline;
curve2=animatedline;
curve3=animatedline;
curve2.Color='blue';
curve3.Color='red';
set(ax2,'Xlim',[1 365],'Ylim', [min(T1) max(T1)], 'Position',[0.13,0.11,0.775,0.29], 'plotboxaspectratio',[1,0.31,0.31])
grid on
addpoints(curve1,m(i),n(i));
hold on
addpoints(curve2,m(i),T1(i));
addpoints(curve3,m(i),T2(i));
drawnow;
pause(0.1)
else
grid on
addpoints(curve1,m(i),n(i));
addpoints(curve2,m(i),T1(i));
addpoints(curve3,m(i),T2(i));
drawnow;
pause(.1);
end
end

Best Answer

Create the subplot and modify their position before the loop. Make sure to pass the axes to the hold() and grid() calls.
At present you keep calling subplot and then modify the position. However each time you call subplot it figures out where the plot belongs based on the n m index parameters, and if it finds any axes that over overlap those coordinates but not exactly the same coordinates then it deletes the old one. So subplot() all your axes into existence first before you set the position of any of them, and record the axes handles and do not subplot in a loop unless you do not mind old axes potentially being deleted.