Creator
Creator

Reputation: 33

How to plot on the same figure with different data and delete the old plot(s)

For faster operation I want to update a plot with different data in MATLAB. If I use plot3 it will open a new figure every time, which is time consuming. I cannot use hold command as I do not want earlier plots. Any suggestion?

Upvotes: 2

Views: 640

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Create the plot object initially and then update its 'XData','YData' and 'ZData' properties according to the new values:

axis([0 1 0 1]);
h = plot3(NaN,NaN,NaN,'.'); %// intiallize plot object
for n = 1:20
    x = rand(1,100);
    y = rand(1,100);
    z = rand(1,100); %// example new data for the plot
    set(h, 'XData', x, 'YData', y, 'ZData', z); %// update properties of plot object
    pause(.1)
end

Upvotes: 3

Robert Seifert
Robert Seifert

Reputation: 25232

This is the short version of one of my previous answers to a different question.

If you want to create a new plot to the previous figure window by using Plot Objects/functions like e.g. plot3, the hold command is necessary in any case (apart from you're using Core Graphics Objects).

For deleting the previous plots you have two options:

  1. clf (clear figure) which will reset the figure and axes objects (delete all axes objects inside the figure) and therefore is probably not much of a performance plus.
  2. cla (clear axes) which will just clear the axes (delete all graphics objects inside the axes object) but keep all labels and axes limits.

I think the last option is what you're looking for.

Test code:

figure
plot( [10 20], [10 20] );
xlim( [0,100] ); ylim( [0,100] ); hold on
xlabel( 'x' );
ylabel( 'y' );

pause(1)
cla
plot( [20 30], [20 30] );

Upvotes: 1

Related Questions