1 / 38

MatLAB Lesson 3 : Graphics

MatLAB Lesson 3 : Graphics. Edward Cheung email: icec@polyu.edu.hk 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

brosh
Download Presentation

MatLAB Lesson 3 : Graphics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MatLABLesson 3 : Graphics Edward Cheung email: icec@polyu.edu.hk Room W311g 2008m

  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

  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

  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”

  5. Figure Copy Template Setting • Menu  File  Preference

  6. Plot More Than One Variable on Same Graph % Try example as follows:- x=0:pi/100:2*pi; %set an array x range 2Pi y1=sin(x); % y1 is the first function plot(x,y1) y2=sin(x-pi/4); % y2 is the second function hold on % don’t clear the graph plot(x,y2) % plot second graph y3=sin(x-pi/2); % y3 is the third function pause(5) % wait 5 seconds plot(x,y3) % plot y3 on same graph y4=sin(x-pi); % y4 is the last one pause % wait for pressing key plot(x,y4) % then plot y4 hold off % clear the hold % same colour because ‘hold off’ is used

  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’)

  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

  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

  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

  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

  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','MarkerSize',10)

  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 #1 t=linspace(0,2*pi,4); % t->x axis range 2pi plot(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 222 plot(sin(t1))

  14. Multiple Plots Per Figure (Cont.) • Set x axis to radian >> subplot 223 plot(t1,sin(t1)) • Suppose we want the data to fill the axes >> subplot 224 plot(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

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

  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:')

  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 off axes('Position', [0.6 0.2 0.3 0.2]) plot(x,y,'g')

  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.

  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

  20. Example - Title, Legend, Label & Text Function >> % Example disp('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)')

  21. With Symbol & Greek Letters in Text Strings >>% example p.26 t=0:900; plot(t,0.25*exp(-0.005*t)) title('A{\ite}^{\alpha{\itt}}','FontSize',16) ylabel('Amplitude','FontSize',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)

  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')

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

  24. Axis Tick (cont. example) labels={'0',' ','10',' ','20',' ','30',' ','40',' ','50',' ','60',' ','70',' ','80',' ','90',' ','100'} set(gca,'XTickLabel',labels)

  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); grid title('Temperature','FontSize',16)

  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

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

  28. Example on Bar Chart

  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.

  30. Example – bar3h

  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 on area(x,profits,'FaceColor',[.9 .85 .7],'EdgeColor','y','LineWidth',2) hold off set(gca,'XTick',[90:94]) text(92,20,'Expenses') text(91,60,'Profits')

  32. Example on Area Filled Plot

  33. Example on Pie Charts x=[1 3 0.5 2.5 2]; explode=[0 1 0 0 0]; subplot 221 pie(x) % pie chart title('2D-Default') subplot 222 pie(x,explode) % explode pie chart title('2D-explode') subplot 223 pie3(x) % 3D pie chart title('3D-Default') subplot 224 pie3(x,explode) % 3D explode pie chart title('3D-Default')

  34. Example on Pie Charts

  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')

  36. Example on Histograms

  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)

  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)

More Related