Professional Documents
Culture Documents
Part 1 2D plots
MATLAB has many functions and commands that can be used to create various
types of plots. Some examples like below ones:
Polar plot:
t=0:.01:2*pi;
polar(t,abs(sin(2*t).*cos(2*t)));
Line plot:
x=0:0.05:5;,y=sin(x.^2);,plot(x,y);
Stem plot:
x = 0:0.1:4;, y = sin(x.^2).*exp(-x);
stem(x,y)
Mesh plot:
z=peaks(25);, mesh(z);
Surface plot:
z=peaks(25);, surf(z);, colormap(jet);
Contour plot:
z=peaks(25);,contour(z,16);
2D Plots
Plot title
Legend
y axis
label
1000
Text
Tick-mark
INTENSITY (lux)
800
Comparison between theory and experiment.
600
400
Data symbol
known as
marker
200
10
12
x axis
label
14
16
DISTANCE (cm)
18
20
22
24
Tick-mark label
7.5
10
6.5
5.5
A plot can be created by the commands shown below. This can be done in the
Command Window, or by writing and then running a script file.
Once the plot command is executed, the Figure Window opens this plot.
Line
Style
Solid
dotted
dashed
dash-dot
Specifier
:
--.
Line
Color
red
green
blue
Cyan
magenta
yellow
black
Specifier
r
g
b
c
m
y
k
Marker Specifier
Type
plus sign
circle
asterisk
point
square
diamond
+
o
*
.
s
d
1988
1989
1990
1991
1992
1993
1994
Sales (M)
127
130
136
145
158
178
211
Line Specifiers:
dashed red line and
asterisk markers.
0.5 x
y 3.5
cos(6x)
for 2 x 4
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
Calculating a value of y
for each x.
Once the plot command is executed, the Figure Window opens with the following
plot.
A PLOT OF A FUNCTION
0.5 x
y 3.5
cos(6x)
for 2 x 4
x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
plot(x,y,u,v,t,h)
Plots three graphs in the same plot:
y versus x, v versus u,
and h versus t.
plot(x,y,-b,u,v,r,t,h,g:)
derivatives, for
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
2 x 4
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
FORMATTING PLOTS
A plot can be formatted to have a required appearance.
FORMATTING COMMANDS
title(string)
Adds the string as a title at the top of the plot.
xlabel(string)
Adds the string as a label to the x-axis.
ylabel(string)
Adds the string as a label to the y-axis.
FORMATTING COMMANDS
legend(string1,string2,string3)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.
text(x,y,string)
Places the string (text) on the plot at coordinate x,y relative to
the plot axes.
gtext(string)
Places the string (text) on the plot. When the command
executes the figure window pops and the text location is clicked
with the mouse.
y=95000./x.^2;
xd=[10:2:22];
xlabel('DISTANCE (cm)')
ylabel('INTENSITY (lux)')
legend('Theory','Experiment',0)
Creating text.
Creating a legend.
The plot that is obtained is shown again in the next slide.
= f(x)
fplot(function,limits)
The function is typed in as a string.
The limits is a vector with the domain of x, and optionally with limits
of the y axis:
[xmin,xmax]
or
[xmin,xmax,ymin,ymax]
y x 2 4 sin(2x) 1
for 3 x 3
fplot(@(x) sin(x+pi/5),'Linewidth',2);
hold on
fplot(@(x) sin(x-pi/5),'--or');
fplot(@(x) sin(x),'-.*c')
hold off
xt = @(t) cos(3*t);
yt = @(t) sin(2*t);
fplot(xt,yt)
saveas(fig_x,[outpath,xy_scatter.tif]);
copy and paste line 77
adjust figure handle and name of file
Supporting Commands
Several functions let you control the plot appearance
axis(): determines the axis scaling (see help for options)
hold on/off: controls whether or not the plot is erased before another
plot is drawn (toggles if no argument given)
>> x=0:0.1:2*pi;
>> plot(x,sin(x))
>> axis
ans =
0
7
-1
>> axis([0 7 -.5 .5])
>> x=0:0.1:2*pi;
>> plot(x,sin(x))
>> hold on
>> plot(x,cos(x))
1
0.5
0.5
-0.5
-0.5
-1
>> plot(x,cos(x),'r:')
>> hold on
>> plot(x,sin(x),'b--')
1
>>
>>
>>
>>
>>
x=0:0.02:1;
y=x.^1.5;
yr=randn(size(x));
yy=y+0.1.*yr;
plot(x,yy,'rx')
x=0:.02:1;
y=x.^1.5;
yr=randn(size(x));
yy=y+0.1.*yr;
plot(x,yy,'ro',x,yy)
1.2
1.2
1
1
0.5
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
-0.5
0
-0.2
-1
-0.2
0
0.2
0.4
0.6
0.8
0.2
0.4
0.6
0.8
>>
>>
>>
>>
>>
>>
1.2
15
10
0.8
x=0:0.2:2.*pi;
y=sin(x);
yr=randn(size(x));
plot(x,10.*y+yr,'ro')
hold on
plot(x,10.*y)
0.6
0
0.4
-5
0.2
-10
0
-0.2
0.2
0.4
0.6
0.8
-15
=
=
=
=
=
0.0:pi/100:2*pi;
cos(X);
3*cos(X);
cos(2*X);
sin(X);
>>
>>
>>
>>
>>
plot(X,Y1)
hold on
plot(X,Y2)
plot(X,Y3)
plot(X,Y4)
-1
-2
-3
Or we could do this:
>> Z = [Y1;Y2;Y3;Y4];
>> plot(X,Z)
-1
-2
-3
-1
-2
-3
>>
>>
>>
>>
x=0:0.1:3.*pi;
y1=sin(x+0.5);
y2=90.*sin(x-0.5);
plot(x,y1,x,y2)
100
50
0.5
-50
-0.5
-100
-1
10
x=0:0.1:3.*pi;
y1=sin(x+0.5);
y2=90.*sin(x-0.5);
plotyy(x,y1,x,y2)
100
50
-50
-100
10
Multiple Y-Axes
x=linspace(.1,10,1000);
Describes the behavior of
damp=0.05;
vibrating systems
y=1./sqrt((1-x.^2).^2 + (2.*damp.*x).^2);
plot(x,y)
1
y
1/ 2
semilogx(x,y)
(1 x 2 )2 (2 x )2
loglog(x,y)
10
10
10
10
-1
10
0
10 -1
10
-2
10
10
1
-1
10 10
10
10
Subplot Command
There are times when it is better to create several smaller plots arranged
in some kind of grid; subplot(m,n,k) does this
m=rows, n=columns in the grid
k=current focus (numbered row-wise)
Lets define a 2x3 subplot grid for: subplot(2,3,1) with the focus
on the first plot.
3
1
Subplots
SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index)
subplot(2,2,1);
plot(1:10)
subplot(2,2,2)
x = 0:.1:2*pi;
plot(x,sin(x))
subplot(2,2,3)
x = 0:.1:2*pi;
plot(x,exp(-x),r)
subplot(2,2,4)
plot(peaks)
subplotex
LOGLOG
Both axes
logarithmic
SEMILOGY
log Y
linear X
SEMILOGX
log X
linear Y
PLOTYY
2 sets of
linear axes
other_axes
On Your Own:
Putting it all together
X=0:0.5:50;
Y=5*x.^2;
subplot(2,2,1), plot(X,Y), title(Polynomial Linear/Linear), ...
ylabel(y), grid
subplot(2,2,2), semilogx(X,Y), title(Polynomial Log/Linear), ...
ylabel(y), grid
Specialized 2D Plots
There are a number of other specialized 2D plots
41
Bar Graphs
MATLAB will plot horizontal and vertical bar graphs
Pie Charts
MATLAB can also make pie charts
Stem Plots
And stem plots for discrete data
45
46
Histograms
A histogram is a plot showing the distribution of a set
of values
47
Stem()
stem()is to plot discrete sequence data
The usage of stem() is very similar to plot()
cos(n/4)
1
>>
>>
>>
>>
n=-10:10;
f=stem(n,cos(n*pi/4))
title('cos(n\pi/4)')
xlabel('n')
0.5
-0.5
-1
-10
-5
0
n
10
Bar
C_suger = [1 2 3];
kid1_score = [7;8;9];
kid2_score = [6;6;10];
kid3_score = [5;5;10];
kids_scores =[kid1_score,kid2_score,
kid3_score];
figure;
subplot(3,1,1)
bar(C_suger,kids_scores);
title('bar ''group''');
legend('Kid1','Kid2','Kid3');
subplot(3,1,2)
bar(C_suger,kids_scores, 'stacked');
title('bar ''stacked''');
legend('Kid1','Kid2','Kid3');
subplot(3,1,3)
barh(C_suger,kids_scores);
title('group barh');
legend('Kid1','Kid2','Kid3');
Hist /Histc
x=-3:0.1:3;
y = randn(1,1000);
figure;
subplot(3,1,1);
# bins
hist(y,50);
title('hist - k bins');
subplot(3,1,2);
Centers of bins
hist(y,x);
title('hist - bin centers given by x');
subplot(3,1,3);
edges of bins
[n,bin] = histc(y,x);
n=n/sum(n);
Converting to percent
bar(x,n);
title('histc & bar');
of values
Fills a polygon
(connecting start to end)
t =(1:2:15)'*pi/8;
x = sin(t);
y = cos(t);
fill(x,y,'r');
axis square off;
text(0,0,'STOP','Color', [1 1 1], ...
52
Polar Plots
Some functions are easier to specify using polar coordinates than by
using rectangular coordinates
For example the equation of a circle is
y=sin(x)
in polar coordinates
53
54
Example:
t=[0:0.1:10];
polar(t,t);
90
120
150
10
8
6
4
2
60
30
180
(x,y)=(tcost, tsint)
0
210
330
240
300
270
Logarithmic Plots
A logarithmic scale (base 10) is convenient when
a variable ranges over many orders of magnitude, because the wide range of
values can be graphed, without compressing the smaller values.
data varies exponentially.
Aplot uses a linear scale on both axes
semilogy uses a log10 scale on the y axis
semilogx uses a log10 scale on the x axis
loglog use a log10 scale on both axes
56
57
58
To use this, we will need to write another M-file to define our own
special function.
myfun will contain the function name as a string (or explicit call)
we must specify the start, stop values and number of points
Executing:
>> [x,y]=evaluate('trig',0,5.*pi,100);
>> plot(x,y), xlabel('x'), ylabel('y')
>>
-5
10
12
14
16
>> x=-0.5:0.05:2;
80
>> y=humps(x);
60
40
20
0
-20
-0.5
0.5
1
x
Minimum
1.5
Using fminbnd()
See help fminbnd and the textbook for many more details about this
function
On your own: figure out how to find zeros (roots)
>> x=-0.5:0.05:2;
>> y=humps(x);
100
0.6370
y =
80
11.2528
60
>> plot(x,y,'ro')
>> hold on
40
>>
20
0
-20
-0.5
0.5
1
x
1.5
Lorenz attractor
The Lorenz attractor defines a 3-dimensional
trajectory by the differential equations:
, r, b are parameters.
dx
( x y)
dt
dy
rx y xz
dt
dz
xy bz
dt
63
64
g
(
t
)
where
y
(0)
y
and
y1
0
2
dt
dt
dt t 0
yN ) for k 1
This is advanced
material you will see this
during numerical
methods course
Solving an ODE:
setup
th
y2
dy1
y2
dt
dy2 d 2 y1 d 2 y
dy
2 2 g (t ) 2
y g (t ) 2 y2 y1
dt
dt
dt
dt
y2 g (t ) 2 y2 y1
or
y 0
1 y1 0
1
g
(
t
)
y2
[T,Y] are the returned values and each row defines a value of t
where the solution is computed along with the corresponding
solutions, yi , in successive columns.
But we need to provide a function to compute f(t,y) whenever
ode45( ) needs it
We also need to specify the start and end times and initial
conditions in the arguments to ode45( )
g
(
t
)
2
1
y2
1
NOTE:
If you need to pass parameter values to compute
the RHS (e.g, zeta or g(t)), these can be added to
the ode45( ) function call (see help ode45)
205x1
205x2
1640
3280
double array
double array
Result is familiar
square pulse with
ringing oscillations
Fall 2006
70
Figure Window
All editing of figure can be done manually in figure window
Can insert title, axis labels, legend, change axis scaling, tick marks and
labels, etc
Essentially anything you can do from function calls you can do by hand in the
figure window
It just takes longer and you have to do it to every figure every time it is created
Figure Window
Four important menus on figure
window
File, edit, insert and tools drop down
menus
Figure Window
File menu
Edit menu
Edit axis properties, figure properties
Insert menu
Insert title, legend, axis labels
Tools menu
Change view of plot, add basic
regression lines
Figure Window
Top toolbar
From left to right:
New figure, open file, save figure, print figure, edit figure,
zoom in , zoom out, pan, rotate 3D, data cursor,
brush/select data, link plot, insert colorbar, insert legend,
hide plot tools, show plot tools and dock figure
Figure Window
Edit plot icon
Probably most important
When selected it allows you to move placement of title, axis labels, legend,
colorbar, any other text or items on plot
Allows you to select objects of the figure to then edit properties of under the
edit menu, edit current object properties option
Figure Window
Plot tools
Clicking on plot tools icon in toolbar opens up plot tools window
Can also be done with plottools from command line or m-file
Easy way to insert text boxes, arrows, other things
Basic Plotting
grid command will turn on x, y-axis grid lines
axis([xmin xmax ymin ymax])
Basic Plotting
xlabel(text)
ylabel(text)
title(text)
These three commands will set the xlabel, ylabel and title of the plot for you
The grid, axis and labeling commands all need to be performed after the plot
command
Basic Plotting
h = plot(x,y)
h is a vector of handles to lineseries objects
This allows you to use h to edit the appearance of the data being plotted (i.e.
line color, line style, line width)
h = figure(n)
h is a handle to figure n
This allows you to modify properties of the figure object
Useful if you are creating many figures and want to modify them at different points in
the program
Modifying Plots
set(h,'PropertyName',PropertyValue,...)
The set command takes object handle h and sets property values for give
property names for that object handle
If h is an array, the property values will be set for all object handles in h
a = get(h,'PropertyName')
get returns the value of a given property
Modifying Plots
gcf stands for get current figure handle
Will return handle of current figure
Modifying Plots
MATLAB has many properties for various objects
We will only go over some of the basics
MATLAB help is great for discovering the rest
Line color
Specified by either an RGB triplet from 0 to 1, or short or
long name
Modifying Plots
Line width
Specified by an integer, default is 0.5 points
Each point is 1/72 of an inch
Line style
Modifying Plots
Line markers
Can choose to add markers at each data point
Can have only markers, no line
Modifying Plots
Example syntax
Edit line style, line width and line color in plot command (with error)
Modifying Plots
You can also quickly specify line style, marker type
and color in the plot command
Modifying Plots
Setting axis tick marks and labels
Use the xtick, ytick, ztick and xticklabel, yticklabel, zticklabel property names
Can specify one or both or none to let MATLAB auto select tick interval and
labels
Puts tick marks at x = 1,3,5
set(gca, 'xtick', []);
Will remove all tick marks
Modifying Plots
Four different ways to set the tick labels
set(gca,'XTickLabel',{'1';'10';'100'}) set(gca,'XTickLabel','1|10|100')
set(gca,'XTickLabel',[1;10;100]) set(gca,'XTickLabel',['1 ';'10 ';'100'])
MATLAB runs through the label array until it labels all tick locations
If label array is too small MATLAB wraps around and begins again
Multiple Lineseries
The plot command can plot up to n lineseries at one time
You can also specify line style, color and marker symbol for each
Contour Plots
Contour Plots
contourf syntax very similar to contour
Can do interactive contour labeling
clabel(C,h,'manual')
Using this function call after a contour call will bring up the figure and let you
manually select where the contours will be labeled
Contour Plots
Contour Plots
Contour labeling done using clabel function as weve
seen
Colormaps
Colormaps can be specified for contour plots
MATLAB has many built in colormaps
colormap(map)
This sets the colormap to the one specified
colormap(map(n))
This will set the colormap and use n colors evenly spaced from the given colormap
Colormaps
Can create your own colormaps
Need to be an array of RGB triplets (3 column array) in the range of 01
Then pass array name to colormap function
Images
a = magic(4)
a =
Use Row 2
of colormap
13 for pixel (1,2)
16
11
10
12
14
15
image(a);
map = hsv(16)
map =
1.0000
1.0000
0.3750
1.0000
0.7500
colormap(map)
imagex
0
0 Row 2
0 .....
Example: Images
load cape
image(X)
colormap(map)
addgraph
h = findobj('Color', [0 0 1])
delete(h)
Practice Problems
x(t ) sin(3t )
y (t ) e 2t 3
5 t 5
0t 5
x(t ) et 2 (2t 1) 0 t 10
Plot the real part and imaginary part of the following signal
x(t ) e0.5t j (t / 3)
0 t 10
For the signal in previous question, plot its phase and magnitude
Try
90
120
60
10
120
60
3
150
150
30
30
150
30
1
180
210
180
210
330
240
90
120
60
4
180
330
240
300
210
330
300
240
270
270
90
90
120
60
0.8
0.6
3
150
30
30
0.4
0.2
1
180
210
330
240
300
270
120
60
4
150
300
270
180
210
330
240
300
270
maxIterations = 500;
gridSize = 1000;
xlim = [-0.748766713922161, -0.748766707771757];
ylim = [ 0.123640844894862,
0.123640851045266];
t = tic();
x = linspace( xlim(1), xlim(2), gridSize );
y = linspace( ylim(1), ylim(2), gridSize );
[xGrid,yGrid] = meshgrid( x, y );
z0 = xGrid + 1i*yGrid;
count = zeros( size(z0) );
z = z0;
for n = 0:maxIterations
z = z.*z + z0;
inside = abs( z )<=2;
count = count + inside;
end
count = log( count+1 );
cpuTime = toc( t );
x=-50:0.5:.50;
y=x;
[X,Y]=meshgrid(x,y);
Z=(cos(X))^2+(cos(Y))^2;
pcolor(X,Y,Z);
shading interp
axis('equal','square','off')