Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

2D Graphics

One of Matlaba most powerful features is the ability to create graphic plots. There are
so many methods of generating graphics in Matlab.
1. X-Y Plots
A Cartesian or x,y plot is based on plotting the x,y data pairs from the specified
vectors. Clearly, the vectors x and y must have the same number of elements. Given a
vector x of x-coordinates x1 through xn and a vector y of y-coordinates y1 through yn,
plot(x,y) graphs the points (x1,y1) through (xn,yn).
For example, to plot the two dimensions corresponding to (0,0), (1,1), (4,2) , (5,1)
and (0,0) points .
x=[0 1 4 5 0];
y=[0 1 2 -1 0];
plot(x,y)
The command plot(x,y) opens a graphics window and draws an x-y plot of the
elements of x versus the elements of y.To plot the graph of y=x3 on the interval [2,2],
first define a row vector whose components range from -2 to 2 in increments of .05.
Then define a vector y; of the same size as x whose components are the cubes of the
components of x. Finally use the plot function to display the graph.
x=-2:.05:2;
y=x.^3;
plot(x,y)
You can, also for example, draw the graph of the sine function over the interval -4 to 4 with
the following commands:
x = -4:.01:4;
y = sin(x);
plot(x,y)
The resulting plot is shown in figure 1.

Figure 1. Plotting sine over the interval -4 to 4


1
Plots of parametrically defined curves can also be made. Try, for example,
t=0:.001:2*pi;
x=cos(3*t);
y=sin(2*t);
plot(x,y)
The resulting plot is shown in figure 2.

Figure 2. Plotting parametrically curves


2. Grid
A dotted grid may be added to the plot by:
grid on
This grid can be removed using grid off.
grid off

3. Controlling Axes
Once a plot has been created in the graphics window you may wish to change the
range of x and y values, this can be done by using the command “axis” as follows:
x =0:.01:1;
y =sin(3*pi*x);
plot(x,y)
axis([-0.5 1.5 -1.2 1.2])
The axis command has four parameters, the first two are the minimum and maximum
values of x to use on the axis and the last two are the minimum and maximum values of y.

2
4. Plotting Line Style
Matlab connects a line between the data pairs described by the vectors. You may
wish to present data points and different type of connecting lines between these points.
Data points can be described by a variety of characters such as ( . , + , * , o and x .).
Various line types, plot symbols and colors may be obtained with plot(x,y,S) where S
is a character string made from one element from any or all the following 3 columns:
Character color Character symbol character line style
b blue . . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example,
plot(x,y,'k+:') plots a black dotted line with a plus at each data point.
plot(x,y,'bd') plots blue diamond at each data point but does not draw any line.
plot(x,y,'y-',x,y,'go') plots the data twice, with a solid yellow line interpolating
green circles at the data points.

5. Annotation
The last step before printing or saving a plot is usually to put a title and label the
axes. You can put labels, titles, and text on a plot by using the commands:
xlabel('text')
ylabel('text')
zlabel('text')
title('text')
text(x,y,'text') places text at position x,y
gtext('text') use mouse to place text
For example the graphs can be given titles, axes labeled, and text placed within the
graph with the following commands;
3
t = 0:0.02*pi:2*pi;
plot(t,sin(t))
xlabel('time');ylabel('amplitude');title('Simple Harmonic Oscillator')
The resulting plot is shown in figure 3.

Figure 3. Using annotation in plot


6. Multi–plots
There are two ways to make multiple plots on a single graph are illustrated by.
6.1 Multiple Data Vectors Plots
You can create multiple graphs by using multiple data vectors, for example:
x=0:.01:2*pi;
y1=sin(x);y2=sin(2*x);y3=sin(4*x);
plot(x,y1,x,y2,x,y3)
The re resulting plot is shown in figure 4.

Figure 4. Multiple plots of sine vectors

4
6.2 Multiple Plots with Hold
Another way is with hold on. The command "hold on" holds the old graph when the
new one is plotted. The axes may, however, become rescaled. "hold on" holds the current
picture; "hold off" releases it (but does not clear the window).
Here is an example. Suppose we want to compare the log function with the square
root function graphically. We can put them on the same plot. By default, both plots will
appear in blue, so we will not know which log. We could make them different colors using
options. Here is the final answer,
x=1:100;
y=log(x);
z=sqrt(x);
plot(x,y,’r’); % plot log in red
hold on;
plot(x,z,’b’); % plot log in blue
hold off;
The resulting plot is shown in figure 5.

Figure 5. Multiple plots with hold

The "hold" command will remain active until you turn it off with the command 'hold
off'.

5
7. Subplot
The graphics window may be split into an m by n array of smaller windows into
which we may plot one or more graphs. The windows are numbered 1 to m by n row–wise,
starting from the top left. All of plot properties such as hold and grid work on the current
subplot individually.
x=0:.01:1;
subplot(221), plot(x,sin(3*pi*x))
xlabel('x'),ylabel('sin (3pix)')
subplot(222), plot(x,cos(3*pi*x))
xlabel('x'),ylabel('cos (3pix)')
subplot(223), plot(x,sin(6*pi*x))
xlabel('x'),ylabel('sin (6pix)')
subplot(224), plot(x,cos(6*pi*x))
xlabel('x'),ylabel('cos (6pix)')

The resulting plot is shown in figure 6.

Figure 7. Using subplot


Subplot(221) (or subplot(2,2,1)) specifies that the window should be split into a 2 by 2 array
and we select the first sub-window.

6
Practice Problems

1) Plot the log of the values from 1 to 100.


2) Plot the parametric curve x = t cos(t), y = t sin(t) for 0 < t < 10.
3) Plot the cubic curve y = x³. Label the axis and put a title "a cubic curve"
on the top of the graph.
5) Plot y=(x3+x+1)/x, for –4< x <4 and –10< y < 10.
6) Plot y=ln(x+1) and y=1-x² on the same window for -2 < x <6 and –4 <y <4.
2
7) Plot cos(x +1) on [-2pi,2pi].

7
8. Specialized 2-D plotting functions
MATLAB includes a variety of specialized plotting in addition to the ones described
above. The following below briefly describes some of the other plotting functions
available in MATLAB.

fplot: evaluates a function and plots 1


the results
Example:
0.5
fplot('sin(1/x)', [0.02 0.2]);

-0.5

-1
0.05 0.1 0.15 0.2

ezplot: simplest way to graph a x2+x+1


function (easy plot). 50
Example: to graph the function
40
y=x²+x+1, you write:
ezplot('x^2+x+1') 30

20

10

0
-5 0 5
x

x2+x+1
If you want to sketch the same
function in between –2 and 2 you simply
write: 6
ezplot('x^2+x+1', [-2, 2])
4

-2 -1 0 1 2
x
11
area Filled area plot. 1
area(X,Y) produces a stacked area
plot suitable for showing the contributions 0.5
of various components to a whole. For
vector X and Y, area(X,Y) is the same as
plot(X,Y) except that the area between 0 0
and Y is filled.
Example: -0.5
t = 0:.01:5*pi;
area(t,sin(t)) -1
0 5 10 15

Example:
x = 0:0.01:1.5; 15
area(x,[(x.^2)',(exp(x))',(exp(x.^2))'])

10

0
0 0.5 1 1.5

semilogx: log-scaled x axis 1


semilogx is the same as plot, except
a logarithmic (base 10) scale is used for 0.8
the X-axis.
Example: 0.6
x=0:0.05:5;
0.4
y=exp(-x.^2);
semilogx(x,y);
0.2
grid
0
-2 -1 0 1
10 10 10 10

12
0
semilogy: log-scaled y axis 10
semilogy is the same as plot, except
a logarithmic (base 10) scale is used for -5
the Y-axis. 10
Example:
x=0:0.05:5;
-10
y=exp(-x.^2); 10
semilogy(x,y);
grid
-15
10
0 1 2 3 4 5

0
10
Loglog: Log-log scale plot.
Loglog is the same as plot, except
logarithmic scales are used for both the X- -5
and Y- axes. 10
Example:
x=0:0.05:5;
-10
y=exp(-x.^2); 10
loglog(x,y);
grid
-15
10 -2 -1 0 1
10 10 10 10

bar: creates a bar graph. 1


bar(X,Y) draws the columns of the
M-by-N matrix Y as M groups of N 0.8
vertical bars. The vector X must be
monotonically increasing or decreasing 0.6
Example:
0.4
x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
0.2
grid on
0
-4 -2 0 2 4

13
Example: 1
x = 0:0.5:2*pi;
bar(x, sin(x)); 0.5

-0.5

-1
-5 0 5 10

barh: horizontal bar graph 3


barh(X,Y) draws the columns of the
M-by-N matrix Y as M groups of N 2
horizontal bars. 1
Example:
x = -2.9:.2:2.9; 0
y = exp(-x.*x); -1
barh(x,y);
-2
-3
0 0.2 0.4 0.6 0.8 1

errorbar: creates a plot with error bars 60


errorbar (X,Y,L) plots the graph of
vector X vs. vector Y with error bars 40
specified by the vectors L and U.
Example:
20
x = [ 1.0 1.3 2.4 3.7 3.8 5.1 ];
y = [ -6.3 -8.7 -5.2 9.5 9.8 43.9 ];
coeff = polyfit(x,y,1) 0
yp=polyval(coeff,x)
e=abs(yp-y) -20
errorbar(x,y,e); grid 1 2 3 4 5
e=
7.6079 1.8509 6.9582 6.8052 7.6242 11.9288

14
90 0.5
polar: creates a plot in polar 120 60
coordinates of angles versus radin
150 0.25 30
polar(theta,rho) makes a plot
using polar coordinates of the angle
theta, in radians, versus the radius rho. 180 0
Example:
t=0:.01:2*pi; 210 330
polar(t,sin(2*t).*cos(2*t));
240 300
270

stem: generates stems at each data point


0.6
Example:
x = 0:0.1:4;
y = sin(x.^2).*exp(-x); 0.4
stem(x,y);
grid 0.2

-0.2
0 1 2 3 4

plotyy: graphs with y tick labels on 0.4 1


the left and right
plotyy(X1,Y1,X2,Y2) plots Y1
versus X1 with y-axis labeling on the left
0.2 0.5
and plots Y2 versus X2 with y-axis
labeling on the right.
Example:
x=-2:0.1:2; 0 0
y1=sin(x);
y2=cos(x); 2 -0.5
plotyy(x,y,x,y2); -0.
-2 -1 0 1 2
grid

15
stairs: creates a graph similar to a 1
bar graph, but without internal lines
Example: 0.8
x = -2.9:.2:2.9;
y = exp(-x.*x); 0.6
stairs(x,y);
title('Stair Chart'); 0.4

0.2

0
-4 -2 0 2 4

UK
pie: Pie chart.
pie(X) draws a pie plot of the data in
the vector X. The values in X are USA
normalized via X/sum(X) to determine NL
the area of each slice of pie.
Example:
x = [1 6 2 1 3 9];
label = {'UK','USA','CH','Dk','SU','NL'};
CH
pie(x, label)
Dk SU

hist: creates a histogram 15


Example:
x=rand(1,100);
hist(x); 10
grid

0
0 0.2 0.4 0.6 0.

16
17

You might also like