MatLab Training Course Notes
Session 3

Instructor: Bill Miller
Dynamic Neuroimaging Laboratory
415.502.3726
http://dnl.ucsf.edu

Topics for Session 3

  1. More with plotting: plot, subplot
  2. Working with figure properties: "handle graphics"
  3. Saving figures

1. More with plotting

- plot can take many arguments in addition to data, including "property,value" pairs for setting line colors, styles etc. The general forms are:

plot(ydata) plot(xdata,ydata,color) plot(xdata,ydata,'property',value,'property',value,...)

- hold [on/off] freezes an existing plot so that more than one set of data can be plotted on the same axes.

- legend is an easy way (but not the only way) to provide a key to your the meaning of plot lines.

Example (right click example files and save them)
load sine1 (x1, y1 - sine)
load sine2 (x2, y2 - inverted sine)
whos see the variables loaded
(sine1: x1,y1; sine2: x2,y2)
figure
plot(x1,y1,'r')plots the first sine wave in red
plot(x2,y2,'color',[0 1 0])replaces first plot with second data, and uses RGB color value for green
hold on freeze - don't erase next plots
plot(x1,y1,'r*')first sine again in red stars on same graph
legend('inverted','normal')put a legend on the axes (movable with the mouse)
cla clears axis
clf clears whole figure

In the above example, we load data for two sine waves (variable pairs x1,y1 and x2,y2). Then, y1 is plotted against x1 in red ('r') using the first form of plot above. The second form of plot puts the inverted sine wave (x2, y2) into the axes in green, using the alternative "property, value" way of specifying colors: "color", and [red green blue] ("RGB") values in a vector (e.g., for green, R and B are 0 and G is 1). However, we've lost the first sine wave plot in the process. Now, using hold on to prevent erasure, we plot the first sine wave again (this time in red stars), overlayed on the green inverted sine wave. Next, we put a legend on the axis, giving one string for each line on the axis, in the order that we plotted the data sets (i.e.,'inverted' comes first because we plotted that sine wave before giving the hold on command). Finally, cla erases all things in the current axis (there's only one in this example), and clf clears everything in the current figure.

You can also plot more than one set of data with a single plot command:

plot(x1,y1,'r',x2,y2,'g*')plots both sine waves

(Check out "help plot" for all the colors, line styles and other types of arguments for this function)

- subplot allows you to easily place many axes on same figure, according to a preset grid.

Syntax: subplot(rows,cols,index)

In MatLab there is no variable that "sets" the number of axes that you put on a figure. Basically, subplot is just a convenient way of specifying the size and location of a new axis; you use is multiple times to put many axes on the same figure.

The first two arguments determine the number of rows and columns that subplot should assume. The index argument determines which position in your row/column grid that you want the axis to be placed. Here are some examples of how the axes are ordered:

  subplot(3,1,i)     subplot(2,2,i)       subplot(3,2,i)
      [ 1 ]           [ 1 ]  [ 2 ]      [ 1 ]  [ 2 ]  [ 3 ]
      [ 2 ]           [ 3 ]  [ 4 ]      [ 4 ]  [ 5 ]  [ 6 ]
      [ 3 ]

The index order is from left to right within a row, and continues on the next row, and so on.

Example
close, clear close figures, and clear variables
load sine1 (see above example for link)
load spine image from MatLab's demos
whos (image variable is X, with color map map)
figure
subplot(2,2,1)create the first axis in a 2x2 grid
plot(x1,y1,'m')plot the sine wave in magenta
subplot(2,2,4)make another axis in the bottom right
image(X) plot the spinal cord image
colormap(map)apply the colormap loaded with the data

So, in this example, we have only plotted two of the four possible axes that will fit on the figure using the positions for a 2x2 grid that subplot calculates each time you call it. Note that if you your subplot command leads to an axis that overlaps an existing axis, the existing axis is deleted, along with any plots in that axis. For instance, we can plot the sine wave assuming a 2-row x 1-column grid, which erases the current sine wave axis and puts the new one in its place (but the spine image below is unaffected):

subplot(2,1,1)
plot(x1,y1,'m')

In these examples using subplot, how does the plot function know in which axes to plot the data? The answer is that when you use subplot, the axis it creates becomes the "current" axis of focus. In fact, you can use subplot to switch the focus among axes on the figure you created with earlier subplot calls, as illustrated here:

subplot(2,2,1)
gca(displays handle of axis 1)
subplot(2,2,4)
gca(handle of axis 4)


2. Working with figure properties: "handle graphics"

All aspects of the figure, axes, plots and images can be modified in MatLab, by manipulating the properties associated with each of those "objects". In order to understand how to do this, it is very helpful to learn a bit about the MatLab graphical engine.

- Hierarchical graphics objects: All the possible graphical objects you can create are organized in a hierarchy as follows:

    Root
     |
    Figure
     |
    Axes (and Uicontrols)
     |
    Image Line Surface Text (and others)

Note: You can see this hierarchy in the on-line help system by typing helpdesk and clicking on the link to "handle graphics", or by going to the equivalent page on MatLab's website.

Each of the above objects has its own set of associated properties, the settings for most of which can be changed by the user.

- Parents and children: The "root" object is a non-displayed object where MatLab stores settings like screen size. When type figure, MatLab generates a figure object and shows it on the screen. It is assigned as a child in the root objects "children" property. The root object is consequently also listed in the figure's "parent" property. Similarly, axes you create on that figure are all listed in the figure "children" property.

- Handles: Each object you create is given a "handle" or reference number automatically. You use these handles to specify which object(s) you want to deal with when changing the value of a particular property. The handle of the root object is always 0. The handles of figure objects are integers starting with 1. All other objects have non-integer handles.

- Changing graphic object properties: the get and set functions allow you to find out what the value of a particular property is, and to change it. The syntax for these commands is:

    get(handle, [property])
    set(handle, [property, value])

With both commands, if you provide only a handle argument, all of the properties for that object are displayed, with their default and possible values (set) or with their actual current values (get).

The following examples refer to a two-axis figure like that we created in the example for subplot above.

Example 1(using the figure created in the earlier subplot example)
load sine1;load spine;create a figure with a plot and an image
subplot(2,1,1);plot(x1,y1,'r')
subplot(2,2,4);image(X)
get(0) list all the root properties
(look for the single entry in "children": handle the figure)
gcf display the handle of the current figure; should match the handle in root's "children" property!
get(gcf) list all the properties for the figure
(look for the "children" handles for the figure axes)
subplot(2,2,1) make the top left axis the current one
gca display the handle of the current axis
get(gca) list all the properties for the current axis
get(gca,'children') list the child objects (handles to plot objects) on the current axis

Example 2(using handles, with the same figure created above)
ha=get(0,'children') ha contains the handles of children of the root object (one figure)
get(ha,'type') lists the type of object for the handle in ha ('figure')
hb=get(ha,'children') hb contains axis handles of the figure
hc=get(hb(1),'children') hc contains the handle of the child object on the first axis in the handle list hb
get(hc,'type') type of child object referred to by handle hc ('image'!)
hd=get(hb(2),'children') handle to child in second axis handle in hb
get(hd,'type') type of this object is 'line'!
set(hd,'color','g') change the color of the line to green

--> Note in the second example above that when we asked for a list of handles of children of the figure (put into the variable hb) the image axis handle was listed first (hb(1)) followed by the line plot axis handle, even though the plot axis had been created first. The handles are listed in reverse order of creation, so that the last created object is listed first. Handle order can be manipulated to change the visual stacking order of overlapping objects.

- Basic axis properties: 'xlim', 'ylim', 'xdata','ydata','title', 'xlabel', 'ylabel'
- Basic plot properties: 'color', 'linewidth', 'linestyle','marker', 'markersize'

The features of an axis you usually want to change/add are the axis limits and the axis labels. For plots, you often want tochange the line color, heaviness (width), style (dash, solid, etc.) and marker type (circles, stars, etc.) from the defaults that MatLab uses. You can make these changes using set with the appropriate properties and values listed above. For axes, MatLab has also provided some easier functions for doing the same thing:

Example(uses figure from above example)
subplot(2,2,1)
title('Sine wave')
xlabel('time')
ylabel('Ampl')
set(gca,'xlim',[0 5],'ylim',[-2 2])(change 2 properties in one set)

The manual "Using MATLAB Graphics" has a very readable description of handle graphics if you want more detail. If you've installed the electronic manuals (PDF files), you can access the graphics manual from the helpdesk --> "Online Manuals". Also see help graphics for a list of many graphics-related functions.


3. Saving figures

MatLab provides several ways of saving and exporting figures you create.

- Menu commands: The following menu commands on the figure's menubar apply to version 5.3 (Release 11) and later:

- Select "Save" from the figure's File menu to save figures in a MatLab "fig" file format that be later reloaded into MatLab and reconstructed.

- Select "Export" from the figure's File menu to save the figure in a variety of different standard formats.

- Select "Print" from the figure's File menu to print the figure directly to a printer. Before you do this, use use the "Page position" and "Page Setup" commands on the figure's File menu to orient the figure on the printed page and set printer settings.

- Select "Copy Figure" from the figure's Edit menu to copy the figure into the clipboard.

- print command: As an alternative to the figure menu commands above (and for Unix/Linux MatLab users of version 5.3), print is the basic command-line figure exporting function to save a figure to a file. It has the following syntax:

	print filename -f(figure handle) [-(format) -(options)] 

The figure handle is the number on the figure window title bar (if turned on); it can also be displayed using gcf when the figure is the active (highlighted) window. The most useful formats and options are as follows (see help print for the whole list):

Postscript:

 -dps    - PostScript for black and white printers
 -dpsc   - PostScript for color printers
 -deps   - Encapsulated PostScript
 -depsc  - Encapsulated Color PostScript

Pictures:

 -djpeg[nn] - JPEG, quality level of nn
 -dtiff     - TIFF
 -dbitmap   - Send figure to clipboard in bitmap format
 -dpict     - Create MacDraw compatible PICT file

Other:

 -append    - Append, not overwrite, the graph to PostScript file
 -noui      - Do not print UI control objects

The following example saves the figure with handle=1 to a file called "session2.ps" with the color Postscript format. (e.g., try this with the figure created in the example in the previous section on handle graphics):

   print session2.ps -f1 -dpsc