PowerPoint to accompany
Introduction to MATLAB
for Engineers, Third Edition
Chapter 5
Advanced Plotting
(cont’d)
Copyright © 2010. The McGraw-Hill Companies, Inc.
This lecture note includes some updates (compared to the original power point of the McGraw-Hill
Companies, Inc.) performed by Asst. Prof. Dr. Neyre Tekbıyık Ersoy for ENGI316 course.
Hints for Improving Plots (Table 5.1-3, page 226)
The following actions, while not required, can nevertheless improve the
appearance of your plots:
1. Start scales from zero whenever possible.
This technique prevents a false impression of the magnitudes of any
variations shown on the plot.
2. Use sensible tick-mark spacing.
If the quantities are months, choose a spacing of 12 because 1/10 of a year
is not a convenient division.
Space tick marks as close as is useful, but no closer.
If the data is given monthly over a range of 24 months, 48 tick marks
might be too dense, and also unnecessary.
3. Minimize the number of zeros in the data being plotted.
For example, use a scale in millions of dollars when appropriate, instead of a
scale in dollars with six zeros after every number.
5-18 (continued …)
Hints for Improving Plots (continued)
4. Determine the minimum and maximum data values for each axis before
plotting the data. Then set the axis limits to cover the entire data range
plus an additional amount to allow convenient tick-mark spacing to be
selected.
For example, if the data on the x-axis ranges from 1.2 to 9.6, a good choice
for axis limits is 0 to 10.
This choice allows you to use a tick spacing of 1 or 2.
5. Use a different line type for each curve when several are plotted on a
single plot and they cross each other;
for example, use a solid line, a dashed line, and combinations of lines and
symbols.
Beware of using colors to distinguish plots if you are going to make black-
and-white printouts and photocopies.
(continued …)
5-19
Hints for Improving Plots (continued)
6. Do not put many curves on one plot, particularly if they will be close to
each other or cross one another at several points.
7. Use the same scale limits and tick spacing on each plot if you need to
compare information on more than one plot.
5-20
Plot enhancement commands
Data Markers and Line Types
To plot y versus x with a solid line and u versus v with
a dashed line, type plot(x,y,u,v,’--’), where the
symbols ’--’ represent a dashed line.
Table 5.2–1 gives the symbols for other line types.
To plot y versus x with asterisks (*) connected with a
dotted line, you must plot the data twice by typing
plot(x,y,’*’,x,y,’:’).
5-24
To plot y versus x with green asterisks (*) connected
with a red dashed line, you must plot the data twice by
typing plot(x,y,’g*’,x,y,’r--’).
5-25
Specifiers for data markers, line types, and colors.
Table 5.2–1, page 228.
Data markers† Line types Colors
Dot (.) . Solid line –– Black k
Asterisk (*) * Dashed line –– Blue b
Cross () Dash-dotted line –. Cyan c
Circle ( ) Dotted line …. Green g
Plus sign (+) + Magenta m
Square ( ) s Red r
Diamond ( ) d White w
Five-pointed star (w) p Yellow y
†Other data markers are available. Search for “markers” in MATLAB help.
5-26
Use of data markers. Figure 5.2–2, page 229.
More?
See
pages
273-274.
5-27
Labeling Curves and Data
The legend command
Automatically obtains from the plot the line type used for each data set
and displays a sample of this line type in the legend box next to the string
you selected.
The following script file produced the plot in Figure 5.2–3 (see next slide).
x = 0:0.01:2;
y = sinh(x);
z = tanh(x);
plot(x,y,x,z,’--’),xlabel(’x’), ...
ylabel(’Hyperbolic Sine and Tangent’), ...
legend(’sinh(x)’,’tanh(x)’)
5-28
Application of the legend command. Figure 5.2–3, page 230
5-29
The hold command
The hold command creates a plot that needs two or more plot
commands.
Example:
Suppose we wanted to plot
versus
where −1 ≤ 𝑥 ≤ 1
on the same plot with the complex function
where 0 ≤ 𝑛 ≤ 10
The following script file creates the plot in Figure 5.2–4.
x = -1:0.01:1;
y1 = 3+exp(-x).*sin(6*x);
y2 = 4+exp(-x).*cos(6*x);
plot((0.1+0.9i).^(0:0.01:10)),hold,plot(y1,y2),...
gtext(‘y2 versus y1’),gtext(‘Imag(z) versus Real(z)’)
5-28
Application of the hold command. Figure 5.2–4, page 231
5-30
Saving Figures
To save a figure that can be opened in subsequent
MATLAB sessions, save it in a figure file with the .fig
file name extension.
To do this, select Save from the Figure window File
menu or click the Save button (the disk icon) on the
toolbar.
If this is the first time you are saving the file, the Save
As dialog box appears. Make sure that the type is
MATLAB Figure (*.fig). Specify the name you want
assigned to the figure file. Click OK.
5-15
Exporting Figures
To save the figure in a format that can be used by another application,
such as the standard graphics file formats TIFF or EPS, perform these
steps.
1. Select Export Setup from the File menu. This dialog lets you specify
options for the output file, such as the figure size, fonts, line size and
style, and output format.
5-16 More? See pages 225-226.
Exporting Figures
2. Select Export from the Export Setup dialog. A standard Save As
dialog appears.
3. Select the format from the list of formats in the Save As type menu.
This selects the format of the exported file and adds the standard file
name extension given to files of that type.
4. Enter the name you want to give the file, less the extension. Then click
Save.
5-16 More? See pages 225-226.
On Windows systems, you can also copy a figure to
the clipboard and then paste it into another
application:
1. Select Copy Options from the Edit menu. The
Copying Options page of the Preferences dialog
box appears.
2. Complete the fields on the Copying Options
page and click OK.
3. Select Copy Figure from the Edit menu.
5-17
Subplots
You can use the subplot command to obtain several smaller
“subplots” in the same figure.
The syntax is subplot(m,n,p).
This command divides the Figure window into an array of rectangular
panes with m rows and n columns.
The variable p tells MATLAB to place the output of the plot command
following the subplot command into the pth pane.
For example, subplot(3,2,5)
Creates an array of six panes, three panes deep and two panes across,
and directs the next plot to appear in the fifth pane (in the bottom-left
corner).
5-21
The following script file created Figure 5.2–1, which shows
the plots of the functions y = e-1.2x sin(10x + 5) for 0 x 5
and y = |x3 - 100| for -6 x 6.
x = 0:0.01:5;
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y),axis([0 5 -1 1])
x = -6:0.01:6;
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y),axis([-6 6 0 350])
The figure is shown
on the next slide.
5-22
Application of the subplot command. Figure 5.2–1
5-23
Logarithmic Plots
It is important to remember the following points when
using log scales:
1. You cannot plot negative numbers on a log scale,
because the logarithm of a negative number is not
defined as a real number.
2. You cannot plot the number 0 on a log scale,
because log10 0 = ln 0 = -. You must choose an
appropriately small number as the lower limit on the
plot.
(continued…)
5-33
Logarithmic Plots (continued)
3. The tick-mark labels on a log scale are the actual
values being plotted; they are not the logarithms of
the numbers. For example, the range of x values in
the plot in Figure 5.3–2 is from 10-1 = 0.1 to 102 =
100.
4. Gridlines and tick marks within a decade are
unevenly spaced. If 8 gridlines or tick marks occur
within the decade, they correspond to values equal
to 2, 3, 4, . . . , 8, 9 times the value represented by
the first gridline or tick mark of the decade.
(continued…)
5-34
Logarithmic Plots (continued)
5. Equal distances on a log scale correspond to
multiplication by the same constant (as opposed to
addition of the same constant on a rectilinear
scale).
For example, all numbers that differ by a factor of 10
are separated by the same distance on a log
scale. That is, the distance between 0.3 and 3 is
the same as the distance between 30 and 300.
This separation is referred to as a decade or cycle.
The plot shown in Figure 5.3–2 covers three decades
in x (from 0.1 to 100) and four decades in y and is
thus called a four-by-three-cycle plot.
5-35
MATLAB has three commands for generating
plots having log scales. The appropriate
command depends on which axis must have a
log scale.
1. Use the loglog(x,y) command to have both
scales logarithmic.
2. Use the semilogx(x,y) command to have the
x scale logarithmic and the y scale rectilinear.
3. Use the semilogy(x,y) command to have the
y scale logarithmic and the x scale rectilinear.
5-36
Logarithmic Plots
Why use log scales? Rectilinear scales A log-log plot can display wide variations in
cannot properly display variations over data values. Figure 5.2-5b, page 233.
wide ranges. Figure 5.2-5a, page 233.
5-31
Exponential and Power Functions Plotted on Log
Scales (Figure 5.2-6, page 235)
x1 = 0:0.01:3; y1 =
25*exp(0.5*x1);
y2 = 40*(1.7.^x1);
x2 = logspace(-1,1,500); y3 =
15*x2.^(0.37);
subplot(1,2,1),semilogy(x1,y1,x1
,y2, '--'),...
legend ('y = 25e^{0.5x}', 'y =
40(1.7)^x'),...
xlabel('x'),ylabel('y'),grid,...
subplot(1,2,2),loglog(x2,y3),leg
end('y = 15x^{0.37}'),...
xlabel('x'),ylabel('y'),grid
5-38
Specialized plot commands. Table 5.2-3, page 236
Command Description
bar(x,y) Creates a bar chart of y versus x.
stairs(x,y) Produces a stairs plot of y versus x.
stem(x,y) Produces a stem plot of y versus x.
5-37
Enhanced Control of Plotted Lines
In previous lecture, we learned how to set the color, style, and marker type for a line.
It is also possible to set four additional properties associated with each line:
• LineWidth—specifies the width of each line in points.
• MarkerEdgeColor—specifies the color of the marker or the edge color for filled
markers.
• MarkerFaceColor—specifies the color of the face of filled markers.
• MarkerSize—specifies the size of the marker in points.
These properties are specified in the plot command after the data to be plotted
in the following fashion:
plot(x,y,'PropertyName',value,...)
For example, the following command plots a 3-point-wide solid black line with
6-point-wide circular markers at the data points. Each marker has a red edge and
a green center, as shown in Figure.
x = 0:pi/15:4*pi;
y = exp(2*sin(x));
plot(x,y,'-ko','LineWidth',3.0,'MarkerSize',6,...
'MarkerEdgeColor','r','MarkerFaceColor','g')
5-48
Enhanced Control of Text Strings
It is possible to enhance plotted text strings (titles, axis labels, etc.) with formatting
such as bold face, italics, and so forth, and with special characters such as
Greek and mathematical symbols. The font used to display the text can be modified by
stream modifiers.
\bf—Boldface.
\it—Italics.
\rm—Remove modifiers, restoring normal font.
\fontname{fontname}—Specify the font name to use.
\fontsize{fontsize}—Specify font size.
_{xxx}—The characters inside the braces are subscripts.
^{xxx}—The characters inside the braces are superscripts.
Enhanced Control of Text Strings
Example:
Solution:
% Script file: ideal_gas.m % Now increase temperature
% Purpose: T = 373; % Temperature (K)
% This program plots the pressure versus volume of an % Calculate volumes
% ideal gas. V = (n * R * T) ./ P;
% % Add second line to plot
% Record of revisions: figure(1);
% Date Programmer Description of change loglog( P, V, 'b--', 'LineWidth', 2 );
% ==== ========== ===================== hold off;
% 01/16/07 S. J. Chapman Original code % Add legend
% legend('T = 273 K','T = 373 k');
% Define variables:
% n -- Number of atoms (mol)
% P -- Pressure (kPa)
% R -- Ideal gas constant (L kPa/mol K)
% T -- Temperature (K)
% V -- volume (L)
% Initialize nRT
n = 1; % Moles of atoms
R = 8.314; % Ideal gas constant
T = 273; % Temperature (K)
% Create array of input pressures. Note that this
% array must be quite dense to catch the major
% changes in volume at low pressures.
P = 1:0.1:1000;
% Calculate volumes
V = (n * R * T) ./ P;
% Create first plot
figure(1);
loglog( P, V, 'r-', 'LineWidth', 2 );
title('\bfVolume vs Pressure in an Ideal Gas');
xlabel('\bfPressure (kPa)');
ylabel('\bfVolume (L)');
grid on;
hold on;
Interactive Plotting in MATLAB
This interface can be advantageous in situations where:
You need to create a large number of different types of
plots,
You must construct plots involving many data sets,
You want to add annotations such as rectangles and
ellipses, or
You want to change plot characteristics such as tick
spacing, fonts, bolding, italics, and colors.
For details, see pages 241-246.
5-42
The interactive plotting environment in MATLAB is a set of
tools for:
Creating different types of graphs,
Selecting variables to plot directly from the Workspace
Browser,
Creating and editing subplots,
Adding annotations such as lines, arrows, text,
rectangles, and ellipses, and
Editing properties of graphics objects, such as their color,
line weight, and font.
5-43
The Figure toolbar displayed. Figure 5.3–1, page 241.
5-44
The Figure and Plot Edit toolbars displayed. Figure 5.3–2,
page 243.
5-45
The Plot Tools interface includes the following three
panels associated with a given figure.
The Figure Palette: Use this to create and arrange
subplots, to view and plot workspace variables, and to
add annotations.
The Plot Browser: Use this to select and control the
visibility of the axes or graphics objects plotted in the
figure, and to add data for plotting.
The Property Editor: Use this to set basic properties
of the selected object and to obtain access to all
properties through the Property Inspector.
5-46
The Figure window with the Plot Tools
activated. Figure 5.3-3, page 244.
5-47
Three-Dimensional Line Plots:
The following program uses the plot3 function to
generate the spiral curve shown in Figure 5.4–1, page
247.
>>t = 0:pi/50:10*pi;
>>plot3(exp(-0.05*t).*sin(t),...
exp(-0.05*t).*cos(t),t),...
xlabel(’x’),ylabel(’y’),zlabel(’z’),grid
See the next slide.
5-48
The curve x = e-0.05t sin t, y = e-0.05t cos t, z = t plotted with the
plot3 function. Figure 5.4–1, page 247.
5-49
Surface Plots:
The following session shows how to generate the
surface plot of the function z = xe-[(x-y2)2+y2], for -2 x 2
and -2 y 2, with a spacing of 0.1. This plot appears in
Figure 5.4–2, page 248.
>>[X,Y] = meshgrid(-2:0.1:2);
>>Z = X.*exp(-((X-Y.^2).^2+Y.^2));
>>mesh(X,Y,Z),xlabel(’x’),ylabel(’y’),...
zlabel(’z’)
See the next slide.
5-50
A plot of the surface z = xe-[(x-y2)2+y2] created with the mesh
function. Figure 5.8–2
5-51
The following session generates the contour plot of the
function whose surface plot is shown in Figure 5.8–2;
namely, z = xe-[(x-y2)2+y2], for -2 x 2 and -2 y 2,
with a spacing of 0.1. This plot appears in Figure 5.4–3,
page 249.
>>[X,Y] = meshgrid(-2:0.1:2);
>>Z = X.*exp(-((X- Y.^2).^2+Y.^2));
>>contour(X,Y,Z),xlabel(’x’),ylabel(’y’)
See the next slide.
5-52
A contour plot of the surface z = xe-[(x-y2)2+y2] created with the
contour function. Figure 5.4–3
5-53
Three-dimensional plotting functions. Table 5.4–1, page 250.
Function Description
contour(x,y,z) Creates a contour plot.
mesh(x,y,z) Creates a 3D mesh surface plot.
meshc(x,y,z) Same as mesh but draws contours under the
surface.
meshz(x,y,z) Same as mesh but draws vertical reference lines
under the surface.
surf(x,y,z) Creates a shaded 3D mesh surface plot.
surfc(x,y,z) Same as surf but draws contours under the
surface.
[X,Y] = meshgrid(x,y) Creates the matrices X and Y from the vectors x
and y to define a rectangular grid.
[X,Y] = meshgrid(x) Same as [X,Y]= meshgrid(x,x).
waterfall(x,y,z) Same as mesh but draws mesh lines in one
5-54 direction only.
Plots of the surface z = xe-(x2+y2) created with the mesh
function and its variant forms: meshc, meshz, and
waterfall. a) mesh, b) meshc, c) meshz, d) waterfall.
Figure 5.4–4, page 250.
publish (‘Lecture_9_examples’,’html’)
open html/Lecture_9_examples.html
5-55