# Safe graphics code

By default, MATLAB's high level plotting commands create the necessary graphics objects so that the user does not have to. For robust use, create and specify graphics objects to avoid overplotting

## Contents

## Simple line plot - replace behaviour

First do a plot

plot( magic(5) )

Do another plot

T = linspace( 0, 5, 1000 ); plot( T, 25*sin( T*10 ) )

## Plot over the top

```
clf
plot( magic(5) )
hold on
plot( T, 25*sin( T*10 ) )
```

## What does "hold" do?

get( gca, 'NextPlot' ) hold off get( gca, 'NextPlot' )

ans = add ans = replace

## Graphics lifecycle

What does the output of plot return?

clf h = plot( magic(5) )

h = 5×1 Line array: Line Line Line Line Line

## Delete one line

Managing the graphics objects directly can be convenient for interactive applications. For example, we can selectively remove a line from the plot by deleting it

delete( h(4) ) h h(4)

h = 5×1 Line array: Line Line Line Line Line ans = handle to deleted Line

## Delete all lines

However, if we delete all lines, we are no longer in the position we started in. A figure window remains, with an axes. Should we have deleted it?

delete( h )

## Creating graphics objects explictly

```
close( gcf )
hFig = figure;
hAxes = axes( 'Parent', hFig );
h = plot( hAxes, magic(5) )
```

h = 5×1 Line array: Line Line Line Line Line

## Deleting parents of graphics objects

isgraphics( h ) delete( hAxes ) isgraphics( h )

ans = 5×1 logical array 1 1 1 1 1 ans = 5×1 logical array 0 0 0 0 0

## Subplot performance

clf tic for n = 1:100 subplot 121 plot( T, 25*sin( T*n ) ) subplot 122 plot( T, 25*cos( T*n ) ) drawnow limitrate end toc

Elapsed time is 1.098528 seconds.

## Subplot performance(2)

clf tic hAxes(1) = subplot(121); hAxes(2) = subplot(122); for n = 1:100 plot( hAxes(1), T, 25*sin( T*n ) ) plot( hAxes(2), T, 25*cos( T*n ) ) drawnow limitrate end toc

Elapsed time is 0.695758 seconds.

## Subplot performance(3)

clf tic hAxes(1) = subplot(121); hAxes(2) = subplot(122); hLine(1) = plot( hAxes(1), T, 25*sin( T ) ); hLine(2) = plot( hAxes(2), T, 25*cos( T ) ); for n = 1:100 hLine(1).YData = 25*sin( T*n ); hLine(2).YData = 25*cos( T*n ); drawnow limitrate end toc

Elapsed time is 0.059666 seconds.