Quantcast

Documentation Center

  • Trial Software
  • Product Updates

Controlling Graphics Output

Figure Targets

MATLAB® allows many figure windows to be open simultaneously during a session. A MATLAB application might create figures to display graphical user interfaces and plotted data. You need to protect some figures from becoming the target for graphics display and to prepare (e.g., reset properties and clear existing objects from) others before receiving new graphics.

Specifying the Target for Graphics Output

By default, MATLAB functions that create graphics objects display them in the current figure and current axes (if it is an axes child). You can direct the output to another parent by explicitly specifying the Parent property with the creating function. For example,

plot(1:10,'Parent',axes_handle)

where axes_handle is the handle of the target axes. The uicontrol and uimenu functions have a convenient syntax that lets you specify the parent as the first argument,

uicontrol(figure_handle,...)
uimenu(parent_menu_handle,...)

or you can set the Parent property. Many plotting functions accept an axes handle as the first argument as well.

Making a Figure and Axes Current

You can specify which figure and which axes within the figure are the target for graphics output. There are two ways to do this.

Making Current and Update.  If figure_handle is the handle to an existing figure, then the statement

figure(figure_handle)
  • Makes figure_handle the current figure.

  • Restacks figure_handle to be the front-most figure displayed.

  • Makes figure_handle visible if it was not.

  • Refreshes figure_handle and process all pending window events.

The same behavior applies to axes. The statement

axes(axes_handle)
  • Makes axes_handle the current axes.

  • Restacks axes_handle to be the front-most axes displayed.

  • Makes axes_handle visible if it was not.

  • Refreshes the figure containing the axes and process all pending window events for that figure.

Make Current Without Changing State.  You can make a figure or axes current without causing MATLAB to change the object's state by setting the figure's root object CurrentFigure property or the figure object's CurrentAxes property to the handle of the figure or axes you want to accept graphics output.

If figure_handle is the handle to an existing figure, the statement

set(0,'CurrentFigure',figure_handle)

makes figure_handle the current figure without changes its state. Similarly, if axes_handle is the handle of an axes object, the statement

set(h,'CurrentAxes',axes_handle)

makes it the current axes, assuming h is the handle of the figure that contains it.

Preparing Figures and Axes for Graphics

By default, commands that generate graphics output display the graphics objects in the current figure without clearing or resetting figure properties. However, if the graphics objects are axes children, MATLAB clears the axes and resets most axes properties to their default values before displaying the objects.

You can change this behavior by setting the figure and axes NextPlot properties.

Using NextPlot to Control Output Target

MATLAB high-level graphics functions check the values of the NextPlot properties to determine whether to add, clear, or clear and reset the figure and axes before drawing. Low-level object-creation functions do not check the NextPlot properties. They simply add the new graphics objects to the current figure and axes.

Low-level functions are designed primarily for use in code files where you can implement whatever drawing behavior you want. However, when you develop a MATLAB-based application, controlling MATLAB drawing behavior is essential to creating a program that behaves predictably.

This table summarizes the possible values for the NextPlot property.

NextPlot

Figure

Axes

new

Create a new figure and use it as the current figure.

Not an option for axes.

add

Add new graphics objects without clearing or resetting the current figure. (Default)

Add new graphics objects without clearing or resetting the current axes.

replacechildren

Remove all child objects, but do not reset figure properties. Equivalent to clf.

Remove all child objects, but do not reset axes properties. Equivalent to cla.

replace

Remove all child objects and reset figure properties to their defaults. Equivalent to clf reset.

Remove all child objects and reset axes properties to their defaults. Equivalent to cla reset. (Default)

A reset returns all properties, except Position and Units, to their default values.

The hold command provides convenient access to the NextPlot properties. The statement

hold on

sets both figure and axes NextPlot properties to add.

The statement

hold off 

sets the axes NextPlot property to replace.

Targeting Graphics Output with newplot

MATLAB provides the newplot function to simplify the process of writing graphics code files that conform to the settings of the NextPlot properties.

newplot checks the values of the NextPlot properties and takes the appropriate action based on these values. Place newplot at the beginning of any code file that calls object creation functions.

When your file calls newplot, the following possible actions occur:

  1. newplot checks the current figure's NextPlot property:

    • If there are no figures in existence, newplot creates one and makes it the current figure.

    • If the value of NextPlot is add, newplot makes the figure the current figure.

    • If the value of NextPlot is new, newplot creates a new figure and makes it the current figure

    • If the value of NextPlot is replacechildren, newplot deletes the figure's children (axes objects and their descendants) and makes this figure the current figure.

    • If the value of NextPlot is replace, newplot deletes the figure's children, resets the figure's properties to the defaults, and makes this figure the current figure.

  2. newplot checks the current axes' NextPlot property:

    • If there are no axes in existence, newplot creates one and makes it the current axes.

    • If the value of NextPlot is add, newplot makes the axes the current axes.

    • If the value of NextPlot is replacechildren, newplot deletes the axes' children and makes this axes the current axes.

    • If the value of NextPlot is replace, newplot deletes the axes' children, resets the axes' properties to the defaults, and makes this axes the current axes.

MATLAB Default Behavior

Consider the default situation where the figure NextPlot property is add and the axes NextPlot property is replace. When you call newplot, it:

  1. Checks the value of the current figure's NextPlot property (which is add) and determines MATLAB can draw into the current figure with no further action. If there is no current figure, newplot creates one, but does not recheck its NextPlot property.

  2. Checks the value of the current axes' NextPlot property (which is replace), deletes all graphics objects from the axes, resets all axes properties (except Position and Units) to their defaults, and returns the handle of the current axes.

Using newplot

To illustrate the use of newplot, this example creates a function similar to the plot function, except it automatically cycles through different line styles instead of using different colors for multiline plots.

function my_plot(x,y)
cax = newplot; % newplot returns handle of current axes
LSO = ['- ';'--';': ';'-.'];
set(cax,'FontName','Times','FontAngle','italic') 
set(get(cax,'Parent'),'MenuBar','none') 
line_handles = line(x,y,'Color','b');
style = 1;
for i = 1:length(line_handles)
    if style > length(LSO), style = 1;end
    set(line_handles(i),'LineStyle',LSO(style,:))
    style = style + 1;
end
grid on

The my_plot function uses the high-level line function syntax to plot the data. This provides the same flexibility in input argument dimension that the plot function supports. The line function does not check the value of the figure or axes NextPlot property. However, because my_plot calls newplot, it behaves the same way the high-level plot function does—with default values in place, my_plot clears and resets the axes each time you call it.

my_plot uses the handle returned by newplot to access the target figure and axes. This example sets axes font properties and disables the figure's menu bar. You obtain the figure handle via the axes Parent property.

This picture shows typical output for the my_plot function.

my_plot(1:10,peaks(10))

Basic Plotting File Structure

This example:

  • Calls newplot early to conform to the NextPlot properties and to obtain the handle of the target axes.

  • References the axes handle returned by newplot to set any axes properties or to obtain the figure's handle.

  • Calls object creation functions to draw graphics objects with the desired characteristics.

The MATLAB default settings for the NextPlot properties facilitate writing function files that adhere to the standard behavior: reuse the figure window, but clear and reset the axes with each new graph. Other values for these properties allow you to implement different behaviors.

Replacing Only the Child Objects — replacechildren

The replacechildren value for NextPlot causes newplot to remove child objects from the figure or axes, but does not reset any property values (except the list of handles contained in the Children property).

This can be useful after setting properties you want to use for subsequent graphs without having to reset properties. For example, if you type at the command line

set(gca,'ColorOrder',[0 0 1],'LineStyleOrder','-|--|:|-.',...
        'NextPlot','replacechildren')
plot(x,y)

plot produces the same output as the my_plot file in the previous section, but only within the current axes. Calling plot still erases the existing graph (i.e., deletes the axes children), but it does not reset axes properties. The values specified for the ColorOrder and LineStyleOrder properties remain in effect.

Testing for Hold State

In some situations your function should change the visual appearance of the axes to accommodate new graphics objects. For example, if you want the my_plot function from the previous example to accept 3-D data, it makes sense to set the view to 3-D when the input data has z-coordinates.

However, to be consistent with the behavior of the MATLAB high-level routines, it is good practice to test whether hold is on before changing parent axes or figure properties. When hold is on, the axes and figure NextPlot properties are both set to add.

The function my_plot3 accepts 3-D data and also checks the hold state, using ishold, to determine whether it should change the view.

function my_plot3(x,y,z)
cax = newplot;
hold_state = ishold; % ishold tests the current hold state
LSO = ['- ';'--';': ';'-.'];
if nargin == 2
    hlines = line(x,y,'Color','k');
    if ~hold_state % Change view only if hold is off
        view(2)
    end
elseif nargin == 3
    hlines = line(x,y,z,'Color','k');
    if ~hold_state % Change view only if hold is off
        view(3)
    end
end
ls = 1;
for hindex = 1:length(hlines)
    if ls > length(LSO),ls = 1;end
    set(hlines(hindex),'LineStyle',LSO(ls,:))
    ls = ls + 1;
end

If hold is on when you call my_plot3, it does not change the view. If hold is off, my_plot3 sets the view to 2-D or 3-D, depending on whether there are two or three input arguments.

Protecting Figures and Axes

In some situations it is important to prevent particular figures or axes from becoming the target for graphics output (i.e., preventing them from becoming the gcf or gca). An example is a figure containing the uicontrols that implement a user interface.

You can prevent MATLAB from drawing into a particular figure or axes by removing its handle from the list of handles that are visible to the newplot function, as well as any other functions that either return or implicitly reference handles (i.e., gca, gcf, gco, cla, clf, close, and findobj). Two properties control handle hiding: HandleVisibility and ShowHiddenHandles.

HandleVisibility Property

HandleVisibility is a property of all objects. It controls the scope of handle visibility within three different ranges. Property values can be:

  • on — The object's handle is available to any function executed on the MATLAB command line or from a file. This is the default.

  • callback — The object's handle is hidden from all functions executing at the command line, even if it is on the top of the screen stacking order. However, during callback routine execution (MATLAB statements or functions that execute in response to user action), the handle is visible to all functions, such as gca, gcf, gco, findobj, and newplot. This setting enables callback routines to take advantage of the MATLAB handle access functions, while ensuring that users typing at the command line do not inadvertently disturb a protected object.

  • off — The object's handle is hidden from all functions executing on the command line and in callback routines. This setting is useful when you want to protect objects from possibly damaging user commands.

For example, if a GUI accepts user input in the form of text strings, which are then evaluated (using the eval function) from within the callback routine, a string such as 'close all' could destroy the GUI. To protect against this situation, you can temporarily set HandleVisibility to off on key objects:

user_input = get(editbox_handle,'String');
set(gui_handles,'HandleVisibility','off')
eval(user_input)
set(gui_handles,'HandleVisibility','on')

Functions Affected by Handle Visibility.  When a handle is not visible in its parent's list of children, functions that obtain handles by searching the object hierarchy or querying handle properties cannot return it. This includes get, findobj, gca, gcf, gco, newplot, cla, clf, and close.

Properties Affected by Handle Visibility.  When you restrict a handle's visibility using callback or off

  • The object's handle does not appear in its parent's Children property

  • Figures do not appear in the root's CurrentFigure property

  • Objects do not appear in the figure's CurrentObject property

  • Axes do not appear in the containing figure's CurrentAxesproperty

Making All Handles Visible.  You can set the root ShowHiddenHandles property to on to make all handles visible, regardless of their HandleVisibility settings (this does not affect the values of the HandleVisibility properties).

Values Returned by gca and gcf.  When a protected figure is topmost on the screen, but has unprotected figures stacked beneath it, gcf returns the topmost unprotected figure in the stack. The same is true for gca. If no unprotected figures or axes exist, calling gcf or gca causes MATLAB to create one in order to return its handle.

Handle Validity Versus Handle Visibility.  All handles remain valid regardless of whether they are visible or not. If you know an object's handle, you can set and get its properties. By default, figure handles are integers that are displayed at the top of the window.

You can provide further protection to figures by setting the IntegerHandle property to off. MATLAB then uses a floating-point number for figure handles.

Accessing Protected Objects

The root ShowHiddenHandlesproperty enables and disables handle visibility control. By default, ShowHiddenHandles is off, which means MATLAB obeys the setting of the HandleVisibility property. When ShowHiddenHandles is set to on, all handles are visible from the command line and within callback routines. This can be useful when you want access to all graphics objects that exist at a given time, including the handles of axes text labels, which are normally hidden.

The close function also allows access to nonvisible figures using the hidden option. For example,

close('hidden') 

closes the topmost figure on the screen, even if it is protected. Combining all and hidden options,

close('all','hidden')

closes all figures.

Was this topic helpful?