Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

## Working with Handle Graphics Objects

### Graphics Objects

Graphics objects are the basic elements used to display graphs and user interface components. These objects are organized into a hierarchy, as shown by the following diagram.

When you call a plotting function, MATLAB® creates the graph using various graphics objects, such as a figure window, axes, lines, text, and so on. Each object has a fixed set of properties, which you can use to control the behavior and appearance of your graph.

For example, the following statement creates a figure with a white background color and does not display the figure toolbar:

figure('Color','white','Toolbar','none')

#### Common Graphics Objects

When you call a function to create a graph, MATLAB creates a hierarchy of graphics objects. For example, calling the plot function creates the following graphics objects:

• Figure — Window that contains axes, toolbars, menus, and so on.

• Axes — Coordinate system that contains the lines representing the data

• Lineseries — Lines that represent the value of data passed to the plot function.

• Text — Labels for axes tick marks and optional titles and annotations.

Different types of graphs use different objects to represent data. All data objects are contained in axes and all objects (except root) are contained in figures.

The root is an abstract object that primarily stores information about your computer or MATLAB states. You cannot create an instance of the root object. The handle of the root object is always 0.

#### Object Handles

When MATLAB creates a graphics object, MATLAB assigns an identifier to the object. This identifier is called a handle. You can use this handle to access the object's properties with the set and get functions. For example, the following statements create a graph and return a handle to a lineseries object in h:

x = 1:10;
y = x.^3;
h = plot(x,y);

You can use the handle h to set the properties of the lineseries object. For example, you can set its Color property:

set(h,'Color','red')

You can also specify the lineseries properties when you call the plotting function:

h = plot(x,y,'Color','red');

You can query the lineseries properties to see the current value:

get(h,'LineWidth')

The get function returns the answer (in units of points for LineWidth):

ans =
0.5000

#### Finding the Properties of an Object

If you call get with only a handle, MATLAB returns a list of the object's properties:

get(h)

If you call set with only a handle, MATLAB returns a list of the object's properties with information about possible values:

set(h)

### Setting Object Properties

All object properties have default values. However, you can change the settings of some properties to customize your graph. There are two ways to set object properties:

• Specify values for properties when you create the object.

• Set the property value on an object that already exists.

#### Setting Properties from Plotting Commands

You can specify object property value pairs as arguments to many plotting functions, such as plot, mesh, and surf.

For example, plotting commands that create lineseries or surfaceplot objects enable you to specify property name/property value pairs as arguments. The command

[x,y,z] = peaks;
surf(x,y,z,...
'FaceColor','interp',...
'EdgeColor',[.7,.7,.7])

plots the data in the variables x, y, and z using a surfaceplot object with interpolated face color and light gray colored edges.

#### Setting Properties of Existing Objects

To modify the property values of existing objects, use the set function. Plotting functions return the handles of the data objects that they create (lines, surfaces, images, and so on). For example, the following statements plot a 5-by-5 matrix (creating five lineseries objects, one per column), and then set the Marker property to square and the MarkerFaceColor property to green:

y = magic(5);
h = plot(y);
set(h,'Marker','s','MarkerFaceColor','g')

In this case, h is a vector containing five handles, one for each of the five lineseries in the graph. The set statement sets the Marker and MarkerFaceColor properties of all lineseries to the same values.

To set a property value on one object, index into the handle array:

set(h(1),'LineWidth',2)

#### Setting Multiple Property Values

If you want to set the properties of each lineseries to a different value, you can use cell arrays to store all the data and pass it to the set command. For example, create a plot and save the lineseries handles:

h = plot(magic(5));

Suppose you want to add different markers to each lineseries and color the marker's face color the same color as the lineseries. You need to define two cell arrays—one containing the property names and the other containing the desired values of the properties.

The prop_name cell array contains two elements:

prop_name(1) = {'Marker'};
prop_name(2) = {'MarkerFaceColor'};

The prop_values cell array contains 10 values: five values for the Marker property and five values for the MarkerFaceColor property. Notice that prop_values is a two-dimensional cell array. The first dimension indicates which handle in h the values apply to and the second dimension indicates which property the value is assigned to:

prop_values(1,1) = {'s'};
prop_values(1,2) = {get(h(1),'Color')};
prop_values(2,1) = {'d'};
prop_values(2,2) = {get(h(2),'Color')};
prop_values(3,1) = {'o'};
prop_values(3,2) = {get(h(3),'Color')};
prop_values(4,1) = {'p'};
prop_values(4,2) = {get(h(4),'Color')};
prop_values(5,1) = {'h'};
prop_values(5,2) = {get(h(5),'Color')};

The MarkerFaceColor is always assigned the value of the corresponding line's color (obtained by getting the lineseries Color property with the get function).

After defining the cell arrays, call set to specify the new property values:

set(h,prop_name,prop_values)

### Functions for Working with Objects

This table lists functions commonly used when working with objects.

Function

Purpose

allchild

Find all children of specified objects.

ancestor

Find ancestor of graphics object.

copyobj

Copy graphics object.

delete

Delete an object.

findall

Find all graphics objects (including hidden handles).

findobj

Find the handles of objects having specified property values.

gca

Return the handle of the current axes.

gcf

Return the handle of the current figure.

gco

Return the handle of the current object.

get

Query the values of an object's properties.

ishandle

True if the value is a valid object handle.

set

Set the values of an object's properties.

### Specifying Axes or Figures

MATLAB always creates an axes or figure if one does not exist when you execute a plotting command. However, when you are creating graphics from a program file, it is good practice to create and specify the parent axes and figure explicitly, particularly if others people use your program. Specifying the parent prevents the following problems:

• Your program overwrites the graph in the current figure. A figure becomes the current figure whenever a user clicks it.

• The current figure might be in an unexpected state and not behave as your program expects.

The following example shows a MATLAB function that evaluates a mathematical expression over the range specified in the input argument x, and then plots the results. A second call to the plot function plots the mean value of the results as a red line.

function myfunc(x)
% Evaluate the expression using the input argument
y = 1.5*cos(x) + 6*exp(-.1*x) + exp(.07*x).*sin(3*x);

% Calculate the mean
ym = mean(y);

% Create a figure, axes parented to that axes
% and the using the axes
hfig = figure('Name','Function and Mean');
hax = axes('Parent',hfig);
plot(hax,x,y)

% Hold the current plot and add a red line along the mean value
hold on
plot(hax,[min(x) max(x)],[ym ym],'Color','red')
hold off

% Add a tick label that shows the mean value
% and add a title and axis labels
ylab = get(hax,'YTick');
set(hax,'YTick',sort([ylab ym]))
title ('y = 1.5cos(x) + 6e^{-0.1x} + e^{0.07x}sin(3x)')
xlabel('X Axis'); ylabel('Y Axis')
end

First, define a value for the input argument and call the function:

x = -10:.005:40;
myfunc(x)

### Finding the Handles of Existing Objects

The findobj function enables you to obtain the handles of graphics objects by searching for objects with particular property values. With findobj you can specify the values of any combination of properties, which makes it easy to pick one object out of many. findobj also recognizes regular expressions.

For example, you might want to find the blue line with square marker having blue face color. You can also specify which figures or axes to begin searching from, if there are more than one. The following four sections provide examples illustrating how to use findobj.

#### Finding All Objects of a Certain Type

Because all objects have a Type property that identifies the type of object, you can find the handles of all occurrences of a particular type of object. For example,

h = findobj('Type','patch');

finds the handles of all patch objects.

#### Finding Objects with a Particular Property

You can specify multiple properties to narrow the search. For example,

h = findobj('Type','line','Color','r','LineStyle',':');

finds the handles of all red dotted lines.

#### Limiting the Scope of the Search

You can specify the starting point in the object hierarchy by passing the handle of the starting figure or axes as the first argument. For example,

h = findobj(gca,'Type','text','String','\pi/2');

finds the string π/2 only within the current axes.

#### Using findobj as an Argument

Because findobj returns the handles it finds, you can use it in place of the handle argument. For example,

set(findobj('Type','line','Color','red'),'LineStyle',':')

finds all red lines and sets their line style to dotted.