Rahav
Rahav

Reputation: 1875

Why is subplot much faster than figure?

I'm building a data analysis platform in MATLAB. One of the system's features need to create many plots. At any given time only one plot is available and the user can traverse to the next/previous upon request (the emphasis here is that there is no need for multiple windows to be open).

Initially I used the figure command each time a new plot was shown, but I noticed that, as the user traverse to the next plot, this command took a bit longer than I wanted. Degrading usability. So I tried using subplot instead and it worked much faster.

Seeing this behavior I ran a little experiment, timing both. The first time figure runs it takes about 0.3 seconds and subplot takes 0.1 seconds. The mean run time for figure is 0.06 seconds with standard deviation of 0.05, while subplot take only 0.002 with standard deviation of 0.001. It seems that subplot is an order of magnitude faster.

The question is: In situation when only one window will be available at any given time, is there any reason to use figure?

Is there any value lost in using `subplot' in general?

(similar consideration can be made even if you can either only once).

Upvotes: 1

Views: 275

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

The call of subplot does nothing else than creating a new axes object with some convenient positioning options wrapped around.

Axes objects are always children of figure objects, so if there is no figure window open, subplot will open one. This action takes a little time. So instead of opening a new figure window for every new plot, it's faster to just create a new axes object by using subplot, as you determined correctly. To save some memory you can clear the previous plot by clf as suggested by Daniel.

As I understood, you don't want to Create axes in tiled positions, rather you just want to create one axes object. So it would be even faster to use the axes command directly. subplot is actually overkill.

If all your plots have the same axes limits and labels, even clf is not necessary. Use cla (clear axes) to delete the previous plot, but keep labels, limits and grid.

Example:

%// plot #1
plot( x1, y2 );
xlim( [0,100] ); ylim( [0,100] );
xlabel( 'x' );
ylabel( 'y' );

%// clear plot #1, keep all settings of axes

%// plot #2
plot( x2, y2 );

...

Upvotes: 3

Daniel
Daniel

Reputation: 36710

Use figure once to create a figure and clf to clear it's content before repainting.

Upvotes: 0

Related Questions