Table Of Contents

Plotting graphs

Plotting graphs is a very common tool for illustrating results in science. MATLAB has many commmands that can be used for creating various kinds of plots.

Easy plots

_images/ezplot_xsq43.png

The simplest buit-in function for plotting an explicit function is ezplot command. For example, we want to plot a parabola on the interval [-1,1]

f(x) = x^2,\quad  -1 \leq x \leq 1

We can simply use the following command:

>> ezplot('x^2',[-1 1])

The first input of ezplot command is a string describing the function. The second input (which is optional) is the interval of interest in the graph. Note that the function description is not necessarily a function in x variable. We can use any variable we like:

>> ezplot('sin(b)',[-2 3])

If the function definition involves some constant parameter, write it explicitly:

>> ezplot('x^2+2')

In this case, if we assign a value 2 to a variable first, says y=2, when executing:

>> y = 2;
>> ezplot('x^2+y')

MATLAB will interpret y as a variable (not a value of 2). Hence, it will create a contour plot of the function

x^2+y = 0.

_images/ezplot_xsq_equals_y43.png

Another related command is fplot. It is used to plot a function with the form y = f(x) between specified limits.

Plot command

The plot command is used to create a two-dimensional plot. The simplest form of the command is:

plot(x,y)

where x and y are each a vector. Both vector must have the same number of elements.

_images/plot_xy_exp39.png

For example:

>> x = 0:0.1:5;
>> y = exp(-x);
>> plot(x,y)

Once the plot command is executed, the figure Window opens and the plot is displayed

The plot appears on the screen in blue which is the default line color.

The plot command has additional arguments that can be used to specify the color and style of the line and the color and type of markers, if any are desired. With these options the command has the form:

plot(x,y,'linespec','PropertyName',PropertyValue)

Line Specifiers (linespec)

Line specifiers are optional and can ce used to define the style and color of the line and the type of markers (if markers are desired). The line style specifiers are:

Line Style Specifier
solid (default) -
dashed --
dotted :
dash-dot -.

The line color specifiers are:

Line Color Specifier
red r
green g
blue b
cyan c
magenta m
yellow y
black k
white w

The marker type specifiers are:

Marker Type Specifier
plus sign +
circle o
asterisk *
point .
cross x
triangle (pointed up) ^
triangle (pointed down) v
square s
diamond d
five-pointed star p
sixed-pointed star h
triangle (pointed left) <
triangle (pointed right) >
_images/plot_xy_2tox_linspec37.png

The specifiers are typed inside the plot command as strings. Within the string, the specifiers can be typed in any order and the specifiers are optional. For example:

>> x = 0:5; y = 2.^x; plot(x,y,'-or')

This command creates a plot with solid red line and the marker is a circle.

Property Name and PropertyValue

Properties are optional and can be used to specify the thickness of the line, the size of the marker, and the colors of the marker’s edge line and fill. The Property Name is typed as a string, followed by a comma and a value for the property, all inside the plot command.

Property Name Description
linewidth the width of the line (default 0.5, possible values are 1,2,3,...)
markersize the size of the marker (e.g., 5,6,... )
markeredgecolor the color of the edge line for filled marker (e.g., r, b)
markerfacecolor the color of the filling for filled markers (e.g, r, b)

_images/plot_xy_expsin_linspec36.png

For example, the command:

>> x = linspace(0,pi,50); y = exp(-x).*sin(8*x);
>> plot(x,y,'--sb','linewidth',2,'markersize',8,'markerfacecolor','g')

creates a plot with a blue dashed line and squares as markers. The linewidth is 2 points and the size of the square markers is 8 points. The marker has green filling.

Formatting a plot

Plots can be formatted by using MATLAB command that follow the plot or fplot commands, or interactively by using the plot editor in the Figure Window. Here we will explain the the first method which is more useful since a formatted plot can be created automatically every time the program is executed.

The xlabel and ylabel command

xlabel and ylabel create description on the x- and y-axes, respectively after we have plotted a graph. The usages are:

>> xlabel('text as string')

and:

>> ylabel('text as string')

The title command

A title can be added to the plot with the command:

>> title('text as string')

The text will appear on the top of the figure as a title.

The text command

A text label can be placed in the plot with the text or gtext commands:

>> text(x,y,'text as string')
>> gtext('text as string')

The text command places the text in the figure such that the first character is positioned at the point with the coordinates x,y (according to the axes of the figure). The gtext command places the text at a position specified by the user (with the mouse).

The legend command

The legend command places a legend on the plot. The legend shows a sample of the line type of each graph that is plotted, and places a label, specified by the user, beside the line sample. The usage is:

>> legend('string 1','string 2',... )
_images/plot_xy_distance30.png

For example, the command:

>> t = linspace(0,10,100); s = t.^2/2;
>> plot(t,s);
>> xlabel('Time (sec)');
>> ylabel('distance (m)');
>> title('Distance as a function of t');
>> legend('distance')

creates a plot shown on the right.

Formatting the texts

The texts in the xlabel, ylabel, title, text and legend commands can be formatted to customize the font, size, style (italic, bold, etc.), and color. Formatting can be done by adding optional PropertyName and PropertyValue arguments following the string inside the command. For example:

>> text(x,y,'text as string','PropertyName',PropertyValue)

Some of the PropertyName are:

Property Name Description
Rotation the orientation of the text (in degree)
FontSize the size of the font (in points)
FontWeight the weight of the characters (light, normal, bold)
Color the color of the text (e.g., r, b, etc.)

Some formatting can also be done by adding modifiers inside the string. For example, adding \bf, \it, or \rm, will create a text in bold font, italic style, and with normal font, rexpectively. A single character can be displayed as a subscript or a superscript by typing _ (the underscore character) or ^ in front of the character, respectively. A long superscript or subscript can be typed inside { } following the _ or the ^. For example:

>> title('\bf The values of X_{ij}', 'FontSize',18)

Greek characters

Greek characters can be included in the text by typing \ (back slash) before the name of the letter.

Character Letter
\alpha \alpha
\beta \beta
\gamma \gamma
\theta \theta
\pi \pi
\sigma \sigma

The axis command

When the plot(x,y) command is executed, MATLAB creates axes with limits that are based on the minimum and maximum values of the elements of x and y. The axis command can be used to change the range of the axes. Here are some possible forms of the axis command:

Commands Description
axis([xmin, xmax, ymin, ymax]) sets the limits of both x and y
axis equal sets the same scale for both axes
axis square sets the axes region to be square
axis tight sets the axis limits to the range of the data

The grid command


_images/plot_xsinx_gridaxis29.png

grid on adds grid lines to the plot. grid off removes grid lines from the plot.

For example:

>> fplot('x^2+4*sin(2*x)-1',[-3 3])
>> grid on
>> axis([-2 2 0 5])



Plotting multiple graphs

In may situations there is a need to make several graphs in the same plot. There are two methods to plot multiple graphs in one figure. One is by using the plot command, the other is by using the hold on, hold off commands.

1. Using the plot command

Two or more graphs can be created in the same plot by typing pairs of vectors inside the plot command. For example:

>> plot(x,y,u,v,s,t)

creates 3 graphs: y vs x, v vs u, and t vs s, all in the same plot. The vector of each pair must have the same length. MATLAB automatically plots the graphs in different colors so that they can be identified. It is also possible to add line specifiers following each pair. For example:

>> plot(x,y,'-bo',u,v,'--rx',s,t,'g:s')

plots y vs x with a solid blue line and circles, v vs u with a dashed red lines with cross signs, t vs s with a dotted green line and square markers.

_images/plot_multiple27.png

For example, we plot the function y = 3x^3-26x+10, and its first derivative y'=9x^2-26 and second derivatives y"= 18x , for -2 \leq x \leq 4 , all in the same plot. A script file that creates these graphs can be written as:

>> x = linspace(-2,4,20);
>> y = 3*x.^3-26*x+10;
>> dy = 9*x.^2-26;
>> ddy = 18*x;
>> ddy = 18*x;
>> plot(x,y,x,dy,x,ddy);
>> legend('y','first derivative','second derivative');

The default colors of multiple graphs in MATLAB start from blue, red, and green, respectively.

2. Using the hold on, hold off command

To plot several graphs using the hold on, hold off commands, one graph is plotted first with the plot command. Then the hold on command is typed. This keeps the Figure Window with the first plot open, including the axis properties and the formatting. Additional graphs can be added with plot commands that are typed next. The hold off command stops this process. It returns MATLAB to the default mode in which the plot command erases the previous plot and resets the axis properties.

_images/plot_holdon26.png

With the data from the previous example, we can plot y and its derivatives by typing commands shown in the script:

>> plot(x,y,'-b');
>> hold on
>> plot(x,dy,'--r');
>> plot(x,ddy,':k');
>> hold off

Logarithmic Scales

The semilogy function plots x data on linear axes and y data on logarithmic axes. The semilogx function plots x data on logarithmic axes and y data on linear axes. The loglog function plots both x and y data on logarithmic axes.

For example, notice the difference between the two commands:

>> x = logspace(0,3,100);
>> y = x.^2;
>> semilogy(x,y)
>> loglog(x,y)

(The logspace creates a vector of 100 elements in log scale with the first element 10^0 and the last element 10^(3).)

Polar plots

The polar command is used to plot functions in polar coordinates. The command has the form:

>> polor(theta,radius,'linespec')
_images/polar20.png

where theta and radius are vectors whose elements define the coordinates of the points to be plotted. The line specifiers are the same as in the plot command. To plot a function r=f(\theta) in a certain domain, a vector for values of \theta is created first, and then a vector r with the corresponding values of f(\theta) is created using element-wise calculation.

For example, a plot of the function

r = 3 \cos^2(\theta/2)+\theta, \quad \mbox{for} \quad  0 \leq \theta \leq 2 \pi

is done by:

>> theta = linspace(0,2*pi,200);
>> r = 3*cos(theta/2).^2+theta;
>> polar(theta,r)

Multiple plots on the same window

Multiple plots on the same page can be created with the subplot command, which has the form:

>> subplot(m,n,p)
_images/subplot20.png

The command divides the Figure Window into mxn rectangular subplots where plots will be created. The subplots are arranged like elements in a mxn matrix where each element is a subplot. The subplots are numbered from 1 through mn. The number increases from left to right within a row, from the first row to the last. The command subplot(m,n,p) makes the subplot p current. This means that the next plot command will create a plot in this subplot.

For example, we create a plot that has 2 rows and 2 columns:

>> subplot(2,2,1);ezplot('sin(x)');
>> subplot(2,2,2);ezplot('exp(-x)');
>> subplot(2,2,3);ezplot('x^2');
>> subplot(2,2,4);ezplot('sin(x)/x');

Multiple Figure Windows

When the plot or any other commands that generates a plot is executed, the Figure Window opens and displays the plot. If a Figure Window is already open and the plot command is executed, a new plot will replace the existing plot. It is also possible to open additional Figure Window. This is done by typing the command figure. Every time the command figure is entered, MATLAB opens a new Figure Window and after than we can enter the plot command to generate a plot in the last active Figure Window.

The figure command can also have an input argument that is an integer figure(n). The number corresponds to the number of a corresponding Figure Window. Figure Windows can be closed with the close command. Several forms of the commmand are:

  • close closes the active Figure Window
  • close(n) closes the nth Figure Window
  • close all closes all Figure Windows that are open

Other types of plots (bar, histogram)

We illustrate various kinds of plots by examples.

1. Vertical bar plots

_images/vbar20.png

Function format: bar(x,y):

>> yr = [1988:1994];
>> sle = [8 12 20 22 18 24 27];
>> bar(yr,sle);xlabel('Year');
>> ylabel('Sales (Millions)');

2. Horizontal bar plots

_images/hbar20.png

Function format: barh(x,y):

>> yr = [1988:1994];
>> sle = [8 12 20 22 18 24 27];
>> barh(yr,sle,'r');
>> xlabel('Year');ylabel('Sales (Millions)');

3. Stairs plots

_images/stairs20.png

Function format: stairs(x,y):

>> k=1:5;pmf = [1/4 1/4 1/4 1/8 1/8];
>> cdf =cumsum(pmf);
>> stairs(k,cdf);

4. Stem plots

_images/stem20.png

Function format: stem(x,y):

>> k=-5:5; Rk = 0.5.^abs(k);
>> stem(k,Rk);

5. Pie plots

_images/pie20.png

Function format: pie(x):

>> grade=[11 18 26 9 5];
>> pie(grade)

6. Histograms

Histograms are plots that show the distribution of data. The overall range of a given set of data points is divided to smaller subranges (bins), and the histogram shows how many data points are in each bin. The height of the bar corresponds to the number of data points in the bin. The simplest form of the command is:

>> hist(y,M)
_images/hist20.png

where y is a vector with the data points, and M is the number of bins. For example, we generate 10000 random numbers according to Gaussian distribution. Its histogram should look like a bell curve (due to e^{-x^2/2} term in the density function). This is done by typing:

>> y = randn(10000,1);
>> hist(y,100)

3-D plots

_images/gaussian8.png

Surface, mesh, and contour plots are convenient ways to represent data that is a function of two independent variables, says z = f(x,y). To plot data, a user must create three equal-sized arrays x,y, and z. The vector x and y contain the x values and the y values, and the vector z contains the function values associated with every point of x and y.

MATLAB function meshgrid makes it easy to create the vector x,y arrays required for these plots. Then we evaluate the function values to plot at each of those (x,y) locations. Finally we call function mesh,surf or contour to create the plot. For example, we plot the 2-dimensional Gaussian density function

z = f(x,y) = e^{-(x^2+y^2)/2}

This is done by typing:

>> [x,y]=meshgrid(-3:0.05:3);
>> z = exp(-0.5*(x.^2+y.^2));
>> mesh(x,y,z)

Exercises

  1. Write a MATLAB script to plot \sin(x) versus \cos(2x) from 0 to 2\pi in steps of \pi/10. The points should be connected by a 2-pt red line and each point should be marked with a 6-pt wide blue circular marker.
  2. Write a MATLAB script to plot the magnitude of G(j \omega) where

G(j \omega) = \frac{1}{(j \omega + 2) (j \omega + 10)}

for \omega = 1 to \omega = 1000 in log scale with 200 points. Plot the graph in log scale for both x and y axes.

  1. The position x as a function of time of a particle that moves along a straight line is given by

x(t) = -0.1t^4+0.8t^3+10t-70

Use subplot command to make the three plots of position, velocity, and acceleration on the same page.

  1. Generate 10000 random numbers according to a uniform distribution on the interval [-5,5]. Plot the histogram of the data and discuss the result.