How to do an animated plot in matlab

If what you want is for the plot to “grow” point by point: the easiest way is to create an empty plot and then update its XData and YData properties at each iteration:

h = plot(NaN,NaN); %// initiallize plot. Get a handle to graphic object
axis([min(DATASET1) max(DATASET1) min(DATASET2) max(DATASET2)]); %// freeze axes
%// to their final size, to prevent Matlab from rescaling them dynamically 
for ii = 1:length(DATASET1)
    pause(0.01)
    set(h, 'XData', DATASET1(1:ii), 'YData', DATASET2(1:ii));
    drawnow %// you can probably remove this line, as pause already calls drawnow
end

Here’s an example1 obtained with DATASET1 = 1:100; DATASET2 = sin((1:100)/6);

enter image description here


1 In case someone’s interested, the figure is an animated gif which can be created by adding the following code (taken from here) within the loop, after the drawnow line:

  frame = getframe(1);
  im = frame2im(frame);
  [imind,cm] = rgb2ind(im,256);
  if ii == 1;
      imwrite(imind,cm,filename,'gif','Loopcount',inf);
  else
      imwrite(imind,cm,filename,'gif','WriteMode','append');
  end

Leave a Comment