Вы находитесь на странице: 1из 33

EAS230 Engineering Computations

Spring 2017 Week 7

Introduction to
Plotting 2D Plotting
Chapman 2.11
Learning Outcomes
By the end of this week, you will be able to:
create basic 2-dimensional (2-D) plots
annotate 2-D plots with a title, labels, legends, and
grid lines,
know the different options for plot line styles,
markers, and legends,
adjust the limits of a plot's axes,
display multiple graphs in the same axes,
display multiple plots in the same figure,
know the options for plotting with logarithmic
scales,
Be able to incorporate a MATLAB plot into other
documents (e.g., Microsoft Word).
Plotting Overview
MATLAB has many commands that can be used for creating
different types of plots.
The plots can be formatted to have a desired appearance.
Several graphs can be created in the same plot, and several plots
can be placed on the same page. When a plot contains several
graphs and/or data points, a legend can be added to the plot as
well.
We will only present an overview of MATLAB's plotting
capabilities. If you are interested in learning all of the possible
plotting features in MATLAB, search for "Specialized Plotting" in
MATLAB's help system.
We will focus on two major topics in plotting:
How to create a plot from a set of data.
How to set the attributes of a plot to get the appearance you desire.
2D-Plot: Example
An example of a simple formatted two-dimensional plot that was
created with MATLAB is shown in Figure. The figure contains two
curves that show the variation of light intensity with distance.
title

legend

ylabel

text

MARKER

xlabel
MATLAB functions for generating plots
MATLAB has many commands that can be used for creating
different types of plots. These include:
Plot type 2D Plots 3D Plots
plot(), fplot()
semilogx(), plot3(),
line graphs
semilogy(), ezplot3()
loglog()
scatter plots (graphs) scatter() scatter3()
histograms (graphs) hist(), histc()
bar charts bar(), barh() bar3(), bar3h()
pie charts pie() pie3()
surface plots (graphs) surf()
mesh plots (graphs) mesh()
contour plots (graphs) contour() contour3()
Line graphs using plot()
The plot(x,y) function is one way to create a
line graph, where the two arguments are row
vectors, both of the same length, that
represent the x and y values to be plotted.
Example:

close
h = [1 2 4 7 8 9.5 10];
v = [2 5.5 7 5.5 4 6 8];
plot(h,v)

Note: plot() draws in a "figure window." If


no figure window is currently open, plot will
open a new figure window. If a figure window
is already open, plot() will replace the
contents of the open figure window. Use the
close() function to close a figure window.
Plotting a Function using plot()
Plotting the function y = f(x) is typically a 3-step process:
x = -2*pi:0.1:2*pi; 1. Define a row vector of domain values.

y = sin(x); 2. Create a row vector of the corresponding range values.

plot(x,y) 3. Use the plot() function to graph the data points.


Formatting the line graph
The plot command has additional, optional 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:

x = -2*pi:pi/10:2*pi;
y = sin(x);
plot(x,y,'-.xm','LineWidth',1)
Line Property
MARKER Line Color Property Name
Style Value
Changing the Style, Marker and/or Color of a Line
A plot line's "style" can be modified with a line specifier string. A
line specifier string contains three code values that represent line
style, marker symbol, and color. The allowable codes for each
value are shown below:
Line Style Marker Symbol Color
Solid line
- + Plus sign ^ Upward triangle r Red
(default)
-- Dashed line o Circle v Downward triangle g Green
: Dotted line * Asterisk > Right triangle b Blue
-. Dash-dot line . Point < Left triangle c Cyan
x Cross p pentagram m Magenta
s Square h hexagram (star) y Yellow
d Diamond k Black
w White
Line graphs using plot()
plot() draws a straight line between each adjacent point defined by
the row vectors, i.e. (x(1), y(1)), (x(2), y(2)), ...
(x(end), y(end)). If your plot does not produce a smooth curve,
add more points to your vector of x values. For example:

x=linspace(-2*pi,2*pi,10); x=linspace(-2*pi,2*pi,100);
y=cos(x); y=cos(x);
plot(x,y) plot(x,y)
Notes about using the specifiers:
The specifiers are typed inside the plot command as strings.
Within the string the specifiers can be typed in any order.
The specifiers are optional. This means that none, one, two,
or all three types can be included in a command.
Some examples:

plot(x,y) A blue solid line connects the


points with no markers
(default).
plot(x,y,r) A red solid line connects the
points.
plot(x,y,--g) A green dashed line connects the
points.
plot(x,y,*) The points are marked with * (no
line between the points).
plot(x,y,k:d) A black dotted line connects the
points that are marked with
diamond markers.
Property Name and Property Value:
Properties are optional and can be used to specify the thickness of
the line, the size of the marker, and the colors of the markers
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.
Example
x = -2*pi:pi/10:2*pi;
y = sin(x);
plot(x,y,'-ro','LineWidth',2,'markersize',12,
'MarkerEdgeColor','g','markerfacecolor','y')
Line graphs using fplot()
The fplot command plots a function with the form = ()
between specified limits. The command has the form:

fplot(@(x)function,limits,line specifiers)

The @ sign on The independent The function The domain Specifier for the
the keyboard variable letter written in of x style, color, and
element-wise marker of the line.
format

Using fplot eliminates the need to generate a vector of (x) values.


The fplot function is adaptive it adds more points where the
function is changing rapidly to generate a smooth curve.
function:The function can be typed directly as a string inside the
command in any letter. For example, = 8 2 + 5cos() is typed as:
8*x^2+5*cos(x)or8*t^2+5*cos(t).
limits: The limits argument is a vector with two elements that specify
the domain of x, [xmin,xmax].
Examples:
Example 1:
= 3.50.5 cos(6) for 2 4
>> fplot(@(t)3.5.^(-0.5.*t).*cos(6.*t),[-2,4],':','LineWidth',2)

Example 2:
= 2 + 4 sin 2 1 for 3 3
>> fplot(@(x)x.^2+4*sin(2.*x)-1,[-3,3],'-.r','LineWidth',1)

Example 1: Example 2:
PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT
Multiple lines can be drawn onto a single graph (technically called
a set of axes) in two ways:
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, the command plot(x,y,u,v,t,h)creates three
graphsy vs. x, v vs. u, and h vs. tall in the same plot.
Example: Plot the function = 3 3 26 + 10 , and its first and
second derivatives, for 2 4, all in the same plot.
Solution: The first derivative, = 9 2 26 and the second derivative,
= 18
PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT
Solution: The first derivative, = 9 2 26 and the second derivative,
= 18
PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT
2. Using the hold on and 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.
Additional graphs can be added with plot commands that are typed
next. Each plot command creates a graph that is added to that figure.
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.
%The previous example:
x=[-2:0.01:4];
y=3*x.^3-26*x+6;
yd=9*x.^2-26;
ydd=18*x;
plot(x,y,'-b')
hold on
plot(x,yd,'--r')
plot(x,ydd,':k')
hold off
PLOT FORMATTING/ANOTATING
Annotation Syntax
Add a title title(text as string)
Label the x axis xlabel(text as string)
Label the y axis ylabel(text as string)
Add a grid background grid on
Write text on the graph.
text(x,y,text as string)
(The x,y location is specified
in axes coordinates.)
legend(string1,string2,...)
legend(string1,...,'Location',
'northeastoutside')
Valid locations include:
Add a legend north, south, east, west, northeast,
(to label multiple plot lines) northwest, southeast, southwest,
northoutside, southoutside, eastoutside,
westoutside, northeastoutside,
northwestoutside, southeastoutside,
southwestoutside, best, bestoutside
Example
x = -2*pi:0.1:2*pi;
plot(x,sin(x),'-r',x,cos(x),':b','LineWidth',2)
title('\bfsin(x)&cos(x)')
legend('sin(x)','cos(x)', 'Location','bestoutside')
xlabel('x in [rad]')
ylabel('y')
The axis and grid command:
The axis command:
The limits of the x and y axes is automatically set based on the
minimum and maximum values in the x and y vectors graphed by
plot().
You can modify the limits on each axis using the axis command.
With no arguments, axis() returns a vector with the current plot's
axes limits, in the order: [XMIN XMAX YMIN YMAX]
With a vector of four values as an argument, axis([XMIN XMAX
YMIN YMAX])sets the x and y limits of the current plot.
The grid command:
grid on Adds grid lines to the plot.
grid off Removes grid lines from the plot.
Example: The axis and grid command:
x = -2*pi:0.1:2*pi;
plot(x,sin(x),'-r',x,cos(x),'-.b','LineWidth',1)
title('\bfsin(x)&cos(x)')
legend('sin(x)','cos(x)', 'Location','bestoutside')
xlabel('x in [rad]')
ylabel('y')
axis([-8 8 -1.1 1.1])
grid on
PLOTS WITH LOGARITHMIC AXES

Logarithmic scales (e.g., 1, 10, 100, 1000, ...) are useful for
graphing functions that quickly generate large values along an
axis.
1. The semilogx() function plots x data on a log (base 10) axis
and y data on a linear axis
2. The semilogy() function plots y data on a log (base 10) axis
and x data on a linear axis
3. The loglog() function plots x and y data on logarithmic axes
These three non-linear plot functions have the same usage and
attributes as the plot() function that was described previously.
PLOTS WITH LOGARITHMIC AXES: Examples

Notes for plots with


logarithmic axes:
The number zero
cannot be plotted on
a log scale (since a
log of zero is not
defined).
Negative numbers
cannot be plotted on
log scales (since a
log of a negative
number is not
defined).
PUTTING MULTIPLE PLOTS ON THE SAME PAGE
subplot()
Multiple plots can be created on the same
page (same figure window) with the
subplot command, which has the form:
subplot(r,c,p)
The command divides the Figure Window
into rectangular subplots arranged
like elements in a matrix where each
element is a subplot. The upper left subplot
is numbered 1 and the lower right subplot
is numbered . .
For example, the command
subplot(3,2,1) creates 6 areas
arranged in 3 rows and 2 columns as
shown, and makes the upper left subplot
current.
subplot()Example: 4 Plots

x = -2*pi:0.1:2*pi;
subplot(2,2,1)
plot(x, sin(x))
title('sin(x)')
subplot(2,2,2)
plot(x, cos(x))
title('cos(x)')
subplot(2,2,3)
plot(x, tan(x))
title('tan(x)')
subplot(2,2,4)
plot(x, sinh(x))
title('sinh(x)')
MULTIPLE FIGURE WINDOWS
When plot or any other command that generates a plot is
executed, MATLAB opens a Figure Window (if not already open)
labeled (Figure 1) and displays the plot.
If the Figure Window is already open when the plot command is
executed, a new plot is displayed in the Figure Window (replacing
the existing plot).
It is possible, however, to open additional Figure Windows and
have several of them open (with plots) at the same time. This is
done by typing the command figure. Every time the command
figure is entered, MATLAB opens a new Figure Window.
MATLAB labels the new Figure Windows successively; i.e., Figure
2, Figure 3, and so on.
MULTIPLE FIGURE WINDOWS
close all
fplot(@(x)x.*cos(x),[0,10])
figure
fplot(@(x)exp(-0.2*x).*cos(x),[0,10])

Note: The close command:


close closes the active Figure Window.
close(n) closes the nth Figure Window.
Close all closes all Figure Windows that are open.
Saving/Printing Graphics
Operation Figure Menu Command Syntax Examples
File Print
Print figure
print print
to a printer Windows: Ctrl-P
Mac: P

File Save print myplot -djpeg


Save figure
print filename -dformat print myplot -dbmp
to a file Windows: Ctrl-S
Mac: S print myplot -dtiff

Edit Copy print clipboard dpdf


Copy figure Figure print -clipboard print clipboard dbitmap
to the
-dformat_cb print clipboard dmeta
clipboard Windows: Alt-PrtScr
(Windows only)
Mac: C
Sample Problem: Piston-crank mechanism
Sample Problem: Piston-crank mechanism

Вам также может понравиться