MatLAB Lesson 3 : Graphics

38
1 The Hong Kong Polytechnic University Industrial Centre MatLAB Lesson 3 : Graphics Edward Cheung email: [email protected] Room W311g 2008m

description

MatLAB Lesson 3 : Graphics. Edward Cheung email: [email protected] Room W311g. 2008m. Plotting. Graph is more easy to be read then table in particular to grasp the relationships among variables Horizontal axis is a control variable Plots are normally done in two dimensions - PowerPoint PPT Presentation

Transcript of MatLAB Lesson 3 : Graphics

Page 1: MatLAB Lesson 3 : Graphics

1

The Hong Kong Polytechnic UniversityIndustrial Centre

MatLABLesson 3 : Graphics

Edward Cheung

email: [email protected]

Room W311g

2008m

Page 2: MatLAB Lesson 3 : Graphics

2

Plotting

• Graph is more easy to be read then table in particular to grasp the relationships among variables

• Horizontal axis is a control variable

• Plots are normally done in two dimensions

• Plot File Formats .fig

• MatLab format – double click to open

jpg/bmp/tiff…etc• raster image formats for inserting into reports

Page 3: MatLAB Lesson 3 : Graphics

3

Simple Graph

• Plot graph>> x=0:5;y=0:10:50;plot(x,y)

• Always add title & label all axis – Meaning & Unit!!!>> xlabel('time taken (sec)')ylabel('Distance Travelled (m)')title('Speed of Test Vehicle')title(‘Speed of Mark’’s Vehicle’) % note double apostrophe for Mark‘s

• A new plot() will erase previously defined labels and title

Page 4: MatLAB Lesson 3 : Graphics

4

Single Variable Plotting

>> z=sin(0:0.1:2*pi);plot(z)

What is the size of sample?>> size(z)ans = 1 63 % 1 Dimension 63 Elements >> xlabel('t (0.1 radian)');ylabel('z');title('Function of z')• Note the colour cue when typing (')s - “A hint of warning

on typing mistake”

Page 5: MatLAB Lesson 3 : Graphics

5

Figure Copy Template Setting

• Menu File Preference

Page 6: MatLAB Lesson 3 : Graphics

6

Plot More Than One Variable on Same Graph

% Try example as follows:-x=0:pi/100:2*pi; %set an array x range 2Piy1=sin(x); % y1 is the first functionplot(x,y1)y2=sin(x-pi/4); % y2 is the second functionhold on % don’t clear the graphplot(x,y2) % plot second graphy3=sin(x-pi/2); % y3 is the third functionpause(5) % wait 5 secondsplot(x,y3) % plot y3 on same graphy4=sin(x-pi); % y4 is the last onepause % wait for pressing keyplot(x,y4) % then plot y4hold off % clear the hold

% same colour because ‘hold off’ is used

Page 7: MatLAB Lesson 3 : Graphics

7

Plot more than one function on a graph

% Example (multi-colour plot):-x=-10:10;y=x.^2;plot(x,y,x,2*y,x,3*y,x,4*y)h=findobj(gcf,'linewidth',.5);set(h,'linewidth',2)grid

Usage:-Set(h,’property_name’, ‘property_value’)H=gcf % get current figure handle (e.g. H=1)findobj(‘object_handle’,’property_name’,’property

_value’)

Page 8: MatLAB Lesson 3 : Graphics

8

Basic Plotting/Formatting Functions

• help graphics

• plot(x,y,’linestyle_marker_colour’) – creates an x-y plot

• title(‘string’) – add title to a plot

• xlabel(‘string’) – label x-axis

• ylabel(‘string’) – label y-axis

• grid – grid on/off

• pause – pauses the execution of the program and allow the user to read the graph

• figure – create/index for graph reference >> figure(2)

• hold – on/off – freeze the current plot to allow overlaid

• clf – clear current figure

Page 9: MatLAB Lesson 3 : Graphics

9

Graph Formating

• Line style, colours & markers can be specified with the plot(x,y,s) command S is a character string made from one element

• Usage of line types, plot symbols and colors are given in the help page>> help plot

• Example>> x=0:0.1:2*pi;y=sin(x);plot(x,y,':sg') % colon=>dotted line

• Line style, colours & markers are independent parameters and all must be specified for plotting

Page 10: MatLAB Lesson 3 : Graphics

10

Properties of Graphics

>>get(gcf) % return current figure properties>>get(gca) % return current axis properties

• Linewidth is a scale object The width of the line object. Specify this value in points (1

point = 1/72 inch). The default LineWidth is 0.5 point.>>set(gca,'linewidth',4) % set line width

Page 11: MatLAB Lesson 3 : Graphics

11

Marker Properties

• MarkerSize. The size of the marker, in points. The default value is 6 pts The point marker drawn at 1/3 of the specified size

• MarkerFaceColor. The fill colour for markers that are closed shapes (circle, square, diamond, pentagram, hexagram, and the four triangles). none = interior of the marker transparent auto = same colour as the axis

• MarkerEdgeColor. The colour of the marker or the edge colour for filled markers (circle, square, diamond, pentagram, hexagram, and the four triangles). none = no colour, which makes non-filled markers invisible auto = same colour as the line

Page 12: MatLAB Lesson 3 : Graphics

12

Example on the Properties of Markers

x=-pi:pi/10:pi;y=tan(sin(x))-sin(tan(x));plot(x,y,'--rs','Linewidth',2,...'MarkerEdgeColor','k','MarkerFaceColor','g','Mark

erSize',10)

Page 13: MatLAB Lesson 3 : Graphics

13

Multiple Plots per Figure

• Subplot(m,n,i) breaks the figure into an m-by-n matrix of smaller plots and numbered in row to column>> subplot 221 % 2 x 2 plot #1t=linspace(0,2*pi,4); % t->x axis range 2piplot(sin(t)) % a poor resolution plot

• y = linspace(a,b,n) generates a row vector y of n points linearly spaced between and including a and b. when n is not specified, n=100 function similar to the colon operator

• For a better resolution set n=100>> t1=linspace(0,2*pi);subplot 222plot(sin(t1))

Page 14: MatLAB Lesson 3 : Graphics

14

Multiple Plots Per Figure (Cont.)

• Set x axis to radian>> subplot 223plot(t1,sin(t1))

• Suppose we want the data to fill the axes>> subplot 224plot(t1,sin(t1))axis tight % set axes limit to data range

• axis auto/tight/equal/square/off/on Axes control function>> axis([xmin xmax ymin ymax])

Sets the limit for x & y axes of the current plot

Page 15: MatLAB Lesson 3 : Graphics

15

Axis Limits

• Change axes for a zoom in plotx=0:.01:30;subplot(211)plot(x,x.*sin(x))subplot(212)plot(x,x.*sin(x))axis([10 20 -20 20])

Page 16: MatLAB Lesson 3 : Graphics

16

Three Plots In One Graph

• Example: plotting an underdamped function in 3 views (P.23)>> x=linspace(0,1);y=exp(-x).*cos(6*pi*x);w=exp(-x);z=-w;

subplot(2,2,1)plot(x,y)subplot(2,2,2)

>> plot(x,w,'r:',x,z,'r:')subplot(2,1,2)plot(x,y,x,w,'r:',x,z,'r:')

Page 17: MatLAB Lesson 3 : Graphics

17

Multiple Plots per Figure with Window Plot

x=0:0.05:2*pi;y=sin(x);subplot(2,1,1)plot(x,y,'r')subplot(2,1,2)plot(x,y,'b')axis offaxes('Position', [0.6

0.2 0.3 0.2])plot(x,y,'g')

Page 18: MatLAB Lesson 3 : Graphics

18

Axes

• Axes() Is a function that can be used to create an axes graphics

object in the current figure using default property values.

• The axes Position property enables the user to define the location of the axes within the figure window. h = axes('Position',position_rectangle) axes('position', rect) opens up an axis at the specified

location rect= [left, bottom, width, height] specifies the location and

size of the side of the axis box, relative to the lower-left corner of the Figure window, in normalized units where (0,0) is the lower-left corner and (1.0,1.0) is the upper-right.

Page 19: MatLAB Lesson 3 : Graphics

19

Additional Graph Formatting Functions

• Title(‘string) % discuss already

• Add legend to a graph>>legend(‘string1’, ‘string2’,…)>>legend(‘off’)>>legend(…,pos)>>help legend % give usage

• Arrow & special characters, Greek characters

• Annotation with text()>>text(x,y,‘string1’)

• Add string at (x,y)

>>gtext(‘string’)• Add string at mouse click interactively

Page 20: MatLAB Lesson 3 : Graphics

20

Example - Title, Legend, Label & Text Function

>> % Exampledisp('formatting graph')t=-pi:0.1:pi;plot(t,sin(t),t,cos(t))title('Function of Sine and

Cosine','FontSize',18)xlabel('t=-\pi to \

pi','FontSize',16)ylabel('sin(t) &

cos(t)','Fontsize',16)legend('Sine','Cosine')text(-1,sin(-1),'sin(t)')text(2,cos(2),'cos(t)')

Page 21: MatLAB Lesson 3 : Graphics

21

With Symbol & Greek Letters in Text Strings

>>% example p.26t=0:900;plot(t,0.25*exp(-

0.005*t))title('A{\ite}^{\alpha{\

itt}}','FontSize',16)ylabel('Amplitude','FontS

ize',16)xlabel('Time\mu

sec','FontSize',16)text(300,0.25*exp(-

0.005*300),'\bullet\leftarrow0.25{\ite}^{-0.005{\itt}}at {\itt}=300','FontSize',14)

Page 22: MatLAB Lesson 3 : Graphics

22

Text Properties

• Search for ‘text properties’ in help can get the table of character sequence for Greek or mathematic symbols

• TeX compatible TeX is a cross-platform typesetting freeware

• Reference card http://refcards.com/refcards/tex/tex-refcard-letter.pdf

• What fonts are available?>> c=listfonts % return available fonts

• Try (put abc… on a plot using gtext):->> gtext('\fontname{roman}\fontsize{20}abc')gtext('\fontname{arial}\fontsize{20}\bfabc\fontsize{10}\beta\phi')

Page 23: MatLAB Lesson 3 : Graphics

23

Axis Ticks

t=0:100;plot(t,sin(t/100*2*pi));set(gca,'XTick',0:5:100)grid

Page 24: MatLAB Lesson 3 : Graphics

24

Axis Tick (cont. example)

labels={'0',' ','10',' ','20',' ','30',' ','40',' ','50',' ','60',' ','70',' ','80',' ','90',' ','100'}

set(gca,'XTickLabel',labels)

Page 25: MatLAB Lesson 3 : Graphics

25

Example on Tick & Labels

temp=[21.1 22.2 19.4 23.3 23.9 21.1 20];days={'sun','mon','tue','wed','thur','fri','sat'};plot(1:7,temp); axis([1 7 16 26])set(gca,'XTickLabel',days); gridtitle('Temperature','FontSize',16)

Page 26: MatLAB Lesson 3 : Graphics

26

Bar Chart

• BAR(Y) uses the default value of X=1:M. For vector inputs, BAR(X,Y) or BAR(Y) draws LENGTH(Y) bars. The colors are set by the colormap.

• BAR(X,Y,WIDTH) or BAR(Y,WIDTH) specifies the width of the bars. Values of WIDTH > 1, produce overlapped bars. The default value is WIDTH=0.8

• BAR(...,'grouped') produces the default vertical grouped bar chart.

• BAR(...,'stacked') produces a vertical stacked bar chart.

• BARH Horizontal bar graph

• BAR3 3-D bar graph

• BAR3H Horizontal 3-D bar graph

Page 27: MatLAB Lesson 3 : Graphics

27

Example on Bar Chart

Y=round(rand(5,3)*10)subplot 221bar(Y)title('Group')subplot 222bar(Y,'stack')title('stack')subplot 223barh(Y,'stack')title('stack')subplot 224bar(Y,1.5)title('width=1.5')

Page 28: MatLAB Lesson 3 : Graphics

28

Example on Bar Chart

Page 29: MatLAB Lesson 3 : Graphics

29

Example on Bar3

Y=cool(7);subplot(2,2,1)bar3(Y)title('Default')subplot(2,2,2)bar3(Y,'group')title('Group')subplot(2,2,3)bar3(Y,'stack')subplot(2,2,4)bar3h(Y,'stack')% COOL(M) returns an M-by-3 matrix containing a

"cool" colormap.

Page 30: MatLAB Lesson 3 : Graphics

30

Example – bar3h

Page 31: MatLAB Lesson 3 : Graphics

31

Example on Filled Area Plots

% An area plot displays elements in Y as one or more curves and fills the area beneath each curve.

sales=[51.6 82.4 90.8 59.1 47];x=90:94;profits=[19.3 34.2 61.4 50.5 29.4];area(x,sales,'FaceColor',

[.5 .9 .6],'EdgeColor','b','LineWidth',2)hold onarea(x,profits,'FaceColor',

[.9 .85 .7],'EdgeColor','y','LineWidth',2)hold offset(gca,'XTick',[90:94])text(92,20,'Expenses')text(91,60,'Profits')

Page 32: MatLAB Lesson 3 : Graphics

32

Example on Area Filled Plot

Page 33: MatLAB Lesson 3 : Graphics

33

Example on Pie Charts

x=[1 3 0.5 2.5 2];explode=[0 1 0 0 0];subplot 221pie(x) % pie charttitle('2D-Default')subplot 222pie(x,explode) % explode pie charttitle('2D-explode')subplot 223pie3(x) % 3D pie charttitle('3D-Default')subplot 224pie3(x,explode) % 3D explode pie charttitle('3D-Default')

Page 34: MatLAB Lesson 3 : Graphics

34

Example on Pie Charts

Page 35: MatLAB Lesson 3 : Graphics

35

Example on Histograms

X=randn(10000,3);subplot(2,1,1)hist(X)title('Histogram showing 10 bins')subplot(2,1,2)hist(X,20)title('Histogram showing 20 bins')

Page 36: MatLAB Lesson 3 : Graphics

36

Example on Histograms

Page 37: MatLAB Lesson 3 : Graphics

37

Example on Compass Plot

• COMPASS(U,V) draws a graph that displays the vectors with components (U,V) as arrows emanating from the origin.x=floor(randn(10,1)*10)y=floor(randn(10,1)*10)compass(x,y)

Page 38: MatLAB Lesson 3 : Graphics

38

Compass Plot (Cont. example)

z=[-0.9+5i,-0.9-5i,2.6+3.2i,2.6-3.2i, 3.4811, 1.6+3.2i,1.6-3.2i,-4.3,-0.6+2.7i,-0.6-2.7i]

compass(z)