## Plotting Options and Tips for Matlab

### Topics:

[Back to main page] [Back to "How do I ..."]

### The basics ...

Assuming you have two correctly sized variables (x, the independent variable and y, the dependent variable) the basic scientific plots are created by the following commands:
• x-y plots: plot(x,y)
• semilog plots: semilogy(x,y), semilogx(x,y)
• log-log plots: loglog(x,y)
The on-line help information (try help plot, for example) is quite descriptive and provides good examples to try at the command line.

Sets of x-y data pairs can be plotted simultaneously by just adding pairs in the input list as in

   plot(x1,y1,x2,y2,...)

This allows, for example, data and models to be simultaneously plotted or perhaps data sets of different length to appear on the same axis.

If X and Y have the same number of rows (M) and columns (N) OR if X is M-by-1 and Y is M-by-N then the command

   plot(X,Y)

will create a plot with N different lines, each one generated from the columns of the input arrays.

[TOPICS]

### Plotting data points without the connecting dots

When you use plot in the basic mode, each point defined by the x-y values is connected to the next point by a straight line. If the x- and y-values are closely spaced and in a proper order, the basic mode produces a plot that resembles a smooth curve. However, if the spacing is not fine enough OR if the data is in a random order with respect to the x-values, the "connect-the-dots" effect can be annoying.

To disable the point-to-point connections, you should provide a third argument, the line-style. For example,

   >> plot(x,y,'o')

places a circle at the x-y locations but does not connect successive values. There are many options for plot symbols as well as line styles. See help on plot.

You can plot a line and points simultaneously (in version 5) via a combined command like

   >> plot(x,y,'o-.')
which connects the dots (circles) with a dash-dot line.

[TOPICS]

### Plot title and axis labels

All good engineering plots have appropriate titles and axis labels. The commands for setting the axis labels are xlabel, ylabel and zlabel (for 3D plots). The title for the plot is placed by the title function. Each of these commands take a string as an input.

For example, if you have just plotted your data, use the commands

   >> xlabel('This string goes to the x-axis')
>> ylabel('This string goes to the y-axis')
>> title('This string goes to the title of the plot')



If you make a mistake or want a different title or label, just re-issue the command.

[TOPICS]

### Adding explanatory text to a plot

In addition to a title and axis labels, it is sometimes useful to put one or more lines of informative text within the boundaries of the plot. You have two approaches to accomplish this:

1. Simple: Use gtext

   gtext('A message')


will cause the figure containing your plot to appear along with a cross-hair cursor. Move the cursor to the bottom-left corner of where you want the string to start and then press the mouse button. Repeat the command/click sequence as necessary to get your information across.

Several lines of text can be prepared for several mouse click by using a character array instead of a single string. For example,

   str = char('This is the first line','and this is #2')
gtext(str)


will place the two strings defined by the two rows of str in two mouse clicks (so don't forget to keep clicking).

If your message is a couple of lines long, you can also use a cell array to send the "wrapped" text to gtext. For example,

   str = {'This is line #1','and this is line #2'};
gtext(str)

will place a two-line text message at the location that you click. This approach has the advantages over the character array in that 1) you only need to click a single time and 2) you don't have to worry about lining up the lines.

If you have a single-line string, you can generate an appropriately wrapped, multi-line string using textwrap:

   str = 'This is a line of characters that should be wrapped.'
wrpstr = textwrap(cellstr,15)
gtext(str)

textwrap delivers a cell array, each row of which is a line that is within the width you've set.

Use what works for you.

2. Detailled: Use text

   xpos = {an x-coordinate value}
ypos = {a y-coordinate value}
text(xpos,ypos,'A message')


will start the bottom-left corner of the given text string at the position (xpos,ypos). It is important to be aware that the x- and y-positions should be within the range of the axes that define your plot. Using text is a bit more fussy but ultimately more flexible than gtext.

[TOPICS]

### Legends for complex plots

It is often helpful to provide a key for a plot that has several lines in it. One way of providing such a key is to add text to a figure, each string attached to a particular set of data or lines. This is a particularly simple technique but one that is limited if the plot is complex or the lines/data overlap excessively.

Another way is to add a small box that shows each of the lines (by color or style) along with a descriptive string. In MATLAB, this is accomplished via the legend command.

You use legend after you have created a plot with several lines on it. legend keeps track of how many lines (along with their styles) are in the plot and so only asks you to provide a string for each. It then does all the work of creating a legend.

For example,

   x = 0:0.05:6;
y1 = sin(x);
y2 = sqrt(x);
plot(x,y1,x,y2)
legend('sin(x)','sqrt(x)')

creates a plot with 2 lines and adds a 2-line legend that describes the lines. See the help information on legend for more ways to use this function.

[TOPICS]

### Adding a new line to an existing plot

Sometimes you find yourself in need of adding a line to a plot that already exists. If you were to simply issue a new plot command, the old plot would be lost. To avoid this behavior, use the hold command.
   plot(...)        % create first plot
hold on          % freeze the plot
hold off         % release the plot

You don't need to use hold to add things like titles, axis labels and legends.

[TOPICS]

### Putting more than one plot on a page (subplots)

Sub-dividing a page into separate axes is a common way of increasing the density of information on a page without greatly increasing the complexity of the presentation. MATLAB provides the subplot command as a way to control page sub-division.

Issuing the command

   subplot(M,N,index)
causes the figure window to be divided into an M-by-N array of plot axes. The final input (index) specifies which axis of this array will receive the next plot command that is issued. index should be between 1 and M*N and identifies the axes in the array by counting across the rows and then down the columns.

Here are some useful subplots with the (M,N,index) values given in parentheses:

 (2,2,1) (2,2,2) (2,2,3) (2,2,4)

 (2,2,1) (2,2,2) (2,1,2)

In the second example above, note that different cell sizes can be drawn by controlling the "template" that subplot operates under. As is evident, there is no need to to completely use all axes in particular subdivision.

[TOPICS]

### Including variables in title or axis strings

The title, xlabel and ylabel commands all take strings as inputs. Thus, if you can create a string in a variable, you can provide that variable to any of these functions.

For example, say you wanted to put the date in the title of a plot that is created in an Mfile. Assuming that the plot has been created, you can give the following commands

   dateval = date                          % get the date as string
titlestr = ['Plot created on ',dateval] % create a string
title(titlestr)                         % create the title


The functions num2str and int2str will convert a numeric variable to its string representation. This is especially useful for including values of a parameter in either the title or axis labels.

For example, the following lines will create a 2-by-2 subplot of the function sin(jt) for j = 1,2,3 and 4. For each plot, the value of j is included in the title for the plot using int2str.

   t = linspace(0,7,200);
for j = 1:4
subplot(2,2,j)
plot(t,sin(j*t))
axis([0 7 -1 1])
titlestr = ['Plot of harmonic #',int2str(j)];
title(titlestr)
end

Tighter control of string formatting is available through the sprintf command. Check out the help information on sprintf and its cousin, fprintf.

[TOPICS]

### Being specific about axis limits

The plotting functions in MATLAB do a reasonably good job of setting useful axis limits based on the data you provide. However, there may be times when you want to be a bit more specific and override the default values. The axis command is available for just this operation.

Once you have created a plot, you can issue the axis command in the form

   axis([xlo xhi ylo yhi])

to set the limits of the plot to values that suit you. axis has other uses as well which you can find by reading the on-line help information.
[TOPICS]

### Getting Greek letters (and other goodies) onto plots

Scientific or engineering plots would be pretty boring if the Greek letters used in equations had to be spelled out every time. MATLAB 5.x includes the ability to render LaTex text to get things like Greek letters or exponents to appear in titles and labels. For example,

   title('Results for \beta = 3')


will render a Greek beta in the title of a plot. The "\" that preceeds the word "beta" indicates to MATLAB that the information that directly follows should be rendered as if the type-setting language LaTex were in force (try it). The range of letters (and their appropriate spellings) can be found by issuing the command

   doc text


moving to the Property List section of the page and then clicking on the link to Strings.

Exponents and subscripts require a bit more concentration. For example, to get the string

"Rate coefficient, Ko, in sec-1"

to appear in an axis label, use the command

   xlabel('Rate coefficient, K_o, in sec^{-1}')


The underscore (_) is the indication to LaTex that what follows is to be rendered as a subscript while the caret (^) is the indication to LaTex that what follows should be rendered as a superscript. The braces ({}) serve to define what the underscore or caret is to apply to.

MATLAB's implementation of LaTex is limited but very useful for most common labelling jobs. The online help will be your best guide here.

[TOPICS]

### Some tools for creating nice-looking plots

A strength of MATLAB (in my opinion, anyway) is that it permits you to control many aspects of the plots you create in a (relatively) straightforward way. However, there are times when you might want to use something a bit more interactive or flexible to create that beautiful, informative graphic.

As of version 5.2.1, MATLAB has included a function called plotedit that allows you some measure of interactive titling, labelling and axis control. You have two ways to access this command

1. Issue the command plotedit on (see the help information)
2. Select the "Show Tools" item from the "Tools" menu in a figure window (PC/Unix only)
The WYSIWYG nature of this editor is very nice for generating one-shot plots. Give it a try but remember that the change you make are not saved once the figure is closed.

[TOPICS]

[back to main page] [back to "How do I ..."]
Comments? Contact Jim Maneval at maneval@bucknell.edu