0% found this document useful (0 votes)
38 views11 pages

Class 5

Plotting graphs is a common tool for illustrating results in science. MATLAB has commands for creating various types of plots. The ezplot command is used to easily plot explicit functions by providing the function description as a string and the interval. Formatting options can be applied to plots using commands like xlabel, ylabel, title, text, and legend to add labels and descriptions.

Uploaded by

lucy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views11 pages

Class 5

Plotting graphs is a common tool for illustrating results in science. MATLAB has commands for creating various types of plots. The ezplot command is used to easily plot explicit functions by providing the function description as a string and the interval. Formatting options can be applied to plots using commands like xlabel, ylabel, title, text, and legend to add labels and descriptions.

Uploaded by

lucy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Plotting graphs

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

Easy plots

Fie Edit vhew Insert Tools Desktop Window Heb


The simplest buit-in function for plotting
For
an

explicit function is ezplot command.


to plot a parabola on the
example, we want
interval [-1,1]
0.6 = *", -1 T

We can simply use the fotlowina command:

ezplot ( 'x*2',[-1 11)


U.S

02 The first input of ezplot command is a


string describing the funetion. The second
input (which is optional)is the interval of
interest in the graph. Note that the function
08 08 04 02 0 02 0.4 0.6 .08 ldescription is not necessarily a function in x
variable. We can use any variable we like:

>ezplot (' sin (b) ", [-2 31)

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;
U ezplot ( ' x*2+y')
MATLAB will interpret y as a variable (not a value of 2). Hence, it will ereate'a contour plot of
the function

S2 +y =0

1
CLASS:5

Marker Type Specifier


plus sign
circle
asterisk

point igurd Toos Cesktop Wndow Help


Inset
Fle Edit. Vew
cross

triangle (pointed up)


triangle (pointed down) v
square S

diamond
five-pointed star P
sixed-pointed star h
triangle (pointed left)
triangle (pointed right)
05 1 2253 3
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:

=
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 Property Value

Properties are optionaland can be usedto specify the thickness of the line thesize of the marker.
andthe colors ofthe marker's edgelineand fill. The Property Name istyped 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)
For example, the command:
x
linspace (0, pi, 50); y = exp(-x). *sin (8 *x) ;
p l o t (x, y, '--sb', '1inewidth',2, 'markersize',8, 'marker facecol or "', 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
commands. or
Plots can be formatted by using MATLAB command that follow the plot or fplot
the the first
interaciively by using the plot editor in the Figure Window. Here we'will éxplain time the
method which is more usefu! since a formatted plot can be created automatically every
program is executed.

The xlabel and ylabel comnand

xlabel and vlabel create description onthe x-and y-axes, respectively


after we have plotted a

graph. The usages are:

>>xlabel('text as string') Fle Edit Vew Insert Toos Desktoo Vindow Hep

and:

>> ylabel('text as string' 0

0.6

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. 0, 15

The text command A text label can be placed in


the plot with the text or gtext commands:

> t e x t (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).

5
CLASS.S

T h e 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 sampie. The usage is:
>>
legend ('string 1', 'string 2',...)
Fie Eew iet To

For example, the command: Distance as a functran at

>t
1inspace (0, 10, 100); s =
t.*2/2
>
plot (t, s);
xlabel('Time (sec) ')
ylabel ('distance (m) ');
title ('Distance as a functi on of t')
legend("distá.cc')
ereates a plot shown on the right.
Formatting the texts
The texts in the xlabel, ylabel, title, text and Time is
legend comnands can be formatted to customize
the font, size, style (italic, bold, etc.), and color.
Formatting
can be done by adding
optional
PropertyName and Property Va!ue arguments following the string inside the command. For
example:
t e x t (x, y, 'text as string', ' PropertyNane', Pr opertyvalue)

Some of the PropertyName are

Property Name Description


Rotation the orientation of the text (in degree)
FontSize the size of the font (in
points)
Font Weight the weight of the characters (light, noimal. 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 lbf.
lit, or Im,will create a text in bold font. italicstyle, andwithnormal font, rexpectively. A single
character can be displayed as a subscript or a superscript by typing_(theunderscore character)
or in front ofthe character, respectively. A long superscript or subscript can be typed inside{}
following theor the ^. Forexample:

title ('\bf The values of X_1ij)', 'FontSize ' , 18)


Greek characters
Greek characters can be included in the text by
typing \ (back slash) before the name of the letter.
Character Letteri
Nalpha
beta
gamma
Atheta
pi
sigma
Tie 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

grid on adds grid lines tothe plot. grid off He Et rew nsert oois ird eC
removes grid lines from the plot.
For example:

>fplot ( 'x*2+4*sin (2 *x)-1', [-3 3])9


grid on
>axis ([-2 2 0 51)

Plotting multiple graphs


In may situations there is a need to make several
graphs in the same plot. There are two methods
CLASS:5

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 pBot
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 toadd 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
swith a dotied green line and square markers.

For example, we plot the function y=3a° -20r + 10, and its first derivative
y= 9r - 26and second derivatives = 187, for - 2 4 , all in the samt plot. A

script file that creates these graphs can be written as:


>x
> y
=

=
linspace (-2, 4, 20);
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 defauit colors of multiple graphs in MATLAB start from blue, red, and green, respectively.

2. Using the hold on, hold


off commandTo plot several
File Edt iew Insert Tools Desktoo Window Heb
graphs using the hold on, hold
off commands, one graph is
plotted first with the plot
command. Then the hold on 00 ust de. 3tu
command is typed. This keeps the
80
Figure Window with the first plot
open, including the axis properties 50
and the formatting. Additional
40
graphs can be added with plot
commands that are typed next, 20
The hold off command stops this

20
8
CLASS:5

process. It returns MATLAB to the default mode in which the plot command erases the previous
p l o t and resets the axis properties.
Ea Jset Tods D s t Whoo Hep

tz 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')
hola off

qLogarithmic Scales

The semilogy function plots x data on linear axes and y data on logarith1nic 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 eoFiur 10
Ede Fd ew nsen Iools Deskrop Mindow Help
element 10(3).)

30
10
Polar plots 120

The polar command is used to plot functions in JU

polar coordinates. The command has the form:


160

polor (theta, radius, 'linespec')


210 330

where theta and radius are vectors whose


-

240 J00

elements define the coordinates of the points to 270


be plotted. The line specifiers are the same as in

9
CLASSS

the plot command. To plot a function Oina certain domain, vector for values of Gis a
created first, and then a vector rwith the corresponding values of J (0)is created using
wise calculation. element
For example, a plot of the function
Pi, 1o)
r =
3 cos(0/2) +0. for
theto Itnspace (o,
00 2T
is done by:
T9x cos (theta/2),"2 +helo-
>pola (AkeBo, , - 0 )
>thetalinspace (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)
0Fgure1
Elle Eit Ylew Insert Iools Qesktop Window Help
The command divides the Figure
Wirndow into mxn rectangular
Edlt Plot subplots where plots will be created.
sin) exp- The subplots are arranged like
elements in a mxn matrix where
200
each element is a subplot. The
subplots are numbered from
100
through mn. The number increases
from left to right within a row, from
the first row to the last. The
5 642 0 24
X
command subplot(m.n.p) makes the
subplot p current. This means that
sin/ the next plot command will create a
40
plot jn this sybpl 2 )
20
0.5
e(o,
plot , y )
>aitle C'sina)); subplot 3,3,5)
>Subplo (3,3,2)5 y1dafx);
=coS M);
Plot ,yD
Forexample, we create a plot that has 2 rows and 2 columns:2P10 +ie ('t on))
l e eo 9')
>subplot (2,2, 1);ezplot ( 'sin (x) ");
subplot (2,2,2);ezplot ('exp(-x) ")
(5,5,1); fplot ('sin(t), to, 2*pi3);
sub plot
10 Pij); to,2 *

> subplot (5, 5,); fplot (to9ra)',


sub plot (s,S,3) Aplot tonm). to,pij)5,
subplot 2,2,3) :ezplot('x^2') ;
>>
(2,2,
4);ezplot( n (x) /x'

Multiple Figure Windowvs


When the plot or
opens and displaysanytheother commands that generates a plot is executed, the
executed, a new plot willplot. If a Figure Window is already Figure Window
Window. This is done replace the open and the
existing plot. It is also possible to plot command is
MATLAB opens a new by typing the command figure. Every time the open additional Figure
Figure
generate a plot in the last activeWindow and after than we can enter thecommand figure is entered.
Figure Window. plot command to
The figure command can also have an
corresponds to the number of a input argunment
that is an integer
figure(n). The number
with the close
command. Severalcorresponding Figure Window. Figure Windows
forms of the command are: an be closed'

close closes the active


close(n) closes the nth Figure Window
Figure Window
ciose all closes all
Figure Windows that are open
For example
sgune c);
figure(10)
x=0:0.01:5;
>SAplotC)
>ttguae C2)
plot (ry) fplot C^2')

creates a
plot of y=x, with figure window number as 10. Then
gude )
pot (
close(10) Atgue()
command closes the figure window. >fplot (x^);
Stguoers)
Pplot C'xs');
fig uoe C6)
fplot x°6');
EXERCISE-CLASS 5

with step length n/10.


1. Plot the graph of y=sinx, by taking x=[0,2r)
with step length n/5.
2. Plot the graph of y=sinx, by taking x=[0,2r)
with step length n/5.
3. Plot the graph of y=sinx, by taking x=[0,r]
4. Plot the graph of y=sinx, by taking x=[0,t} with step length
n/10.
5. Plot the graph of ycosx, by taking x=[0,2] with step length r/10.
6. Plot the graph of y=cosx, by taking x=[0,2n] with step length n/5.
7. Plot the graph of y=cosx, by taking x=[0,7] with step length n/10.
8. Plot the graph of y=sinx, by taking x=[0,n] with step length n/5.
9. Plot thee graph of y=sin2x, by taking x=[0,2n] with step length r/10.
10. Plot the graph of y=sin(x/2), by taking x=[0,2r] with step length n/10
11. Plot the graph of y=cos2x, by taking x=[0,2n} with step length n/10.
12. Piot the eraph ot y=costx/2), by laking x=[0,2n) with step length r/10
13. Plot the graph of y=sinx, by taking x={0,2r] with step length n/20,bymaking use of the

commands like iine specifier, line color, line marker.


14. Plot the graph of y=cos, by taking x=[0,2rn] with step length r/2, by making use of the
commands like line specifier, line color, line marker, line width.
15. Plot the graph of y=sin2x, by taking x=[0,2) with step length r/20,bymaking use of the

commands like line specifier, line color, line marker.


1 6 . Plot the graph of y-sin(w/3), by taking x=[0,27] with step length n/20,bymaking use of the
commands liketitle, x label,y label, line color, line marker.
1 7 . Plot the graph of yecos(2x/3), bytaking x=[0,2m] with step length r/20,bymaking use of the
commands like title, x label,y label, line color, line marker, line width.
18. Plot the graph of e'sinx by taking x=l-1,1) with by making use of the commands like fplot,
title, x label,y label, line color, line marker, line width.
19. Plot the graph of cosx.sinx by taking x=(-2,2] with by making use of the commands like

fplot,title, x label ,y label, line color, line marker, line width.


20. Plot the graph of e*sinx by taking x=l-3,3] with by making use of the commandslike
fpiot,title, x label ,y label, line color, line marker, line width.
2 1 . create the graphs of x,2x,3x ina single plot by making use ofthe commands like title, x
label,y label, line color, line marker, line width.
22. create the graphs of x, x, x in a single plot by making use of the commands like title, x
label,y label, line color, line marker, line width.
23. create the graphs of sinx and cosx in a single plot by making use of the commands like
title,x label,y label, line color, line marker, line width
24. create the graphs of x,4+%,8+x in a single plot by making use of the commands like title, x
label,y label, line color, line marker, line width.
25. Plot a polar graph of y=sin2x, by taking x=[0,21) with step length r/20,bymaking use of the
commands like line specifier, line color, line marker.
26. Plot a polar graph of y=cos(/2), by taking x=[0,2n) with step length n/20,bymaking use of
the commands like line specifier, line color, line marker,
27. Plot a polar graph of y=sinx.cosx, by taking x=[0,2] with step length n/20,bymaking use of
the commands like line specifier, line color, line marker,
28. Plot polar graph of y=e'sin2x, by taking x=[0,27n] with
a
step length n/20,bymaking use of the
commands like line specifier, line
color, line marker.
29. Plot a polar graph of
-
y=e"cosx, by taking x={0,2r] with step length
commands like line specifier, line n/20,bymaking use of the
color, line marker.
30. Plot a polar graph of
y=x'sin2x, by taking x=[0,27n] with step length r/20,bymaking use of the
commands like line specifier, line
color, line marker.
31. Plot the graphs of
x,2x,3x with muitiple plots in a single window
commands like title, x label,y label, line by making use of the
32. Plot the graphs of
color, line marker, line width.
x, x', x with multiple plots in a
single window by making use of the
commands like title, x label ,y label, line
color, line marker, line width.
33. Plot the graphs of
sinx ,sin2x, cosx,cos2x with multiple plots in a single window by making
use
of the commands like title, x label,y label, line color, line marker, line width.
34. Plot the graphs of x
,4+x,8+x,16+x with multiple plots in a single window by making use of
the commands like title, x
label,y labei, line color, line marker, ine width.

You might also like