Department of Chemical Engineering
MATLAB Tutorial
 

Plotting Basics                                                                                                         (last updated  9/9/99)

The information in this tutorial is located in the MATLAB manual. Any page or section numbers refer to the following:

The Student Edition of MATLAB, Version 5, The MATH WORKS Inc. Prentice-Hall, 1997.

======================================================================================

This tutorial contains the following sections;

Introduction

Using the plot Command

Linestyles, Markers, and Colors

Adding Grids, Labels, Text, or a Legend

Customizing Axes

Manipulating Plots and Subplotting

Using the pause Command

Plotting a Function Using fplot

Saving Figures

Printing Plots
 
==========================================================================================

Introduction

The purpose of this handout is to cover the basics of creating, editing, and printing graphs. We will only cover 2-dimensional plots in this tutorial. Most of the material presented here is located in Chapter 17 of the MATLAB manual. Chapter 18 covers 3-dimensional plots.

==========================================================================================

Using the plot Command - Section 17.1

In order to show the plot command we need to create some arrays. Create the following m-file.  

 x = linspace(0,4,30);                      %   Reminder: This linspace command creates 30 points equally spaced from 0 and 4.
y = x.^3 - 6*x.^2 + 11*x - 6;       %   The .^ notation is needed to do element by element math.

plot(x,y)                                 %   Create the plot  
 

MATLAB creates the plot by automatically scales the axes, marks the points and connects them with a straight line. It uses its default settings of line types, color, etc.
 

Multiple plots can be put on the same graph. Add the following array to the m-file and replace the plot command. 

z = -x.^3 + 6*x.^2 - 9*x + 3;
plot(x,y,x,z)

Both dependent variables, y and z, could be put into an array, and then the plot command would put both on the graph.

w = [y;z];
plot(x,w)        %   This replaces the previous plot command
 
==========================================================================================

Linestyles, Markers, and Colors - Section 17.2

The table on page 187 of the MATLAB manual gives the available color, symbol types and linestyle options. If you don't specify MATLAB starts with yellow and cycles through the list. The default linestyle is the solid line. The point symbols do not connect the data points with any line type.  The general rule is if you have discrete data, use individual symbols.  Using symbols with a linetype connecting them is acceptable if needed to help the reader follow the data.

The syntax for changing the default color or linestyle settings is plot(x,z,'color linestyle');

plot(x,z,'g+',x,y,'r-.')

If you want to display both a point style and connecting line style you need to plot the data twice.

plot(x,z,'g+',x,z,'g-.')

==========================================================================================

Adding Grids, Labels, Text or a Legend - Section 17.4

To add grid lines at the tick marks on the current plot.  Add this line to your m-file.

grid

The grid can be removed at any time by typing the following in the Command Window..

grid off
 

To add labels to the x and y axes add the following lines to your m-file.

 xlabel('textstring that becomes the label for the x-axis')
ylabel('textstring that becomes the label for the y-axis')
 

To add a title to the graph use the syntax;

>> title('textstring that becomes the label for the graph')
 

You can also add a text string to any specific location on the graph using the format;

text(x,y,'text string')          %   Where x and y are the coordinates for the center, left edge of the text string.
 

An alternative method is to use the 'gtext' command.

gtext('plot 1')
 
Using gtext will change to the current figure, and put a crosshair that follows the mouse. Clicking the mouse will locate the text in the quotes at that location. Be careful, the text can't be removed. The graph must be recreated.

To add a plot legend to your graph, use the syntax;

>>  legend('Trial 1', 'Trial 2')

The linetypes are automatically placed next to the specified label.  To use the the legend command for your name and date, enter them as text strings after the plots.  MATLAB will not place any linetype next to them.  Once it is on the figure, the mouse can be used to drag the legend box where it is desired.  Other options are available under the legend command.  Type help legend to see these.

==========================================================================================

Customizing Axes - Section 17.5

There are a great number of axes commands given in detail in Section 8.2 of the manual. The major commands are summarized on page 150 in Section 5.19.4. The most common use will be;
 

Changing the Default Axes Ranges

 axis([xmin xmax ymin ymax])

This lets you determine the range of the axes.
 

Customizing the tick marks and ticklabels
To set the tick marks to locations other than those seleced by MATLAB use the following command

set(gca,'XTick',[a vector of points where you want the tick marks])

To set the tick labels to other than selected by MATLAB use the following.  These labels are considered to be text and are handled as such.  This most commonly would be done to control the number of decimal points displayed.   Each tick label entry in the list must have the same number of characters.   If  you would like some of the tick marks to be unlabeled, enter the label as the appropriate number of empty spaces.

set(gca,'XTickLabel',['label1'; 'label2'; etc])

label1 and label2 would be something like 1.00, 2.00 etc.
 

Using Log-Log and Semilog Axes

We can also create log or semilog plots. In place of the word plot, use;

==========================================================================================

Manipulating Plots and Subplotting - Section 17.7

If you wish to add another plot to the active figure box instead of replacing it use the hold on command. Create the following m-file.
______________________________________________

%   Darin Ridgway
%   Chemical Engineering
%   Last Updated  -  July 7, 1998

clear        %   Clear the old memory

x = linspace(0,10,21);    %   Create the data to plot
y1 = 2*x + 1;
y2 = 2*x + 2;

 plot(x,y1)                 %   Plot the first data set

 hold on                        %   Hold the current plot

plot(x,y2)                     %   Plot the second plot over the first
_________________________________________________________

Note that both plots are in yellow because they are in separate plot commands. If you want them to be different you must set the color.

Using the hold off command releases the current figure for new plots.

To create a new figure window without closing the current one, use the File/New/Figure command in the MATLAB Command Window or the File/New command in the figure window. You may switch to a new current figure by using the Task Bar at the bottom of the screen or by typing figure(n) at the MATLAB prompt.

One figure window can hold several plotting areas. Use the subplot(m,n,p) to select which area is to be active. This creates a figure with (m x n) plotting areas with the pth one active. Create the following m-file.
_____________________________________________________

%   Darin Ridgway
%   Chemical Engineering
%   Last Updated  -  July 7, 1998

clear        %   Clear the old memory

x = linspace(0,10,21);    %   Create the data to plot
y1 = 2*x + 1;
y2 = 2*x + 2;
y3 = -3*x + 5;
y4 = -2*x + 8;

subplot(2,2,1)                       %   This makes the first plotting area of a 2x2 grid active
plot(x,y1), title('x versus y1')

subplot(2,2,2)                      %   This makes the second plotting area of a 2x2 grid active
plot(x,y2), title('x versus y2')

subplot(2,2,3)                      %   This makes the third plotting area of a 2x2 grid active
plot(x,y3), title('x versus y3')

subplot(2,2,4)                      %   This makes the fourth plotting area of a 2x2 grid active
plot(x,y4), title('x versus y4')
_________________________________________________________________

You can zoom in on a specific area of a figure. Type zoom on at the MATLAB prompt. The current figure will appear. Click on the left mouse button and the figure will increase by a factor of 2 centered around the pointer. The right mouse button zooms back out. To release the zoom feature return to the Command Window type zoom off.

==========================================================================================

Using the Pause Command -  Page 31

If you are creating a plot as part of a larger MATLAB program, you may want the program to create the plot and then wait for you to examine it before proceeding. This is done using the pause command after the plot command. After creating the figure, MATLAB will wait until any key is hit before continuing.

==========================================================================================

Plotting a Function Using the fplot Command  -  Section 16.1

We can also plot a function of one variable between specified limits without creating a data set.   When you have a function you should use fplot so that it appears as a smooth curve, not as discrete points.  The syntax is fplot('function',[xmin xmax]). Where function is the function to be plotted and xmin and xmax are the independent variable limits.
__________________________________
k = 3;
j = 2;
range = [ 0  5 ];
fplot('function_name' , range,[  ], [  ], [  ], k, j)
__________________________________

where the empty brackets are needed if you want to pass parameters to the function file.

The function file would look like the following example.
__________________________________________
function z = function_name(q,k,j)

z = k*q^j*sin(q);
__________________________________________

==========================================================================================
 
Saving Figures

You cannot save figures. You must save an m-file with all the commands used to create the figure. Get in the habit of using m-files to create figures because editing is much easier.

==========================================================================================

Printing Plots

There are two ways to print plots.

(a) In the figure box click on EDIT/COPY OPTIONS
(b) Click on the Windows Metafile format (it is probably already on)
(c) Turn off the Honor figure size properties box
(d) Turn on the White Background box
(e)  Click ON
(e) Click on EDIT/COPY FIGURE
(f) Switch to a word processor document and paste where you want it.
 

If you use a different word processing package you will have to try it with your package. There is a variation in there ability to import and adapt the colors.