Download presentation
Presentation is loading. Please wait.
1
Today’s Lecture Matlab Graphics
Plots and Plotting Tools - How to create and customize data plots using GUI tools Data Exploration Tools - Tools to extract information from graphs interactively Annotating Graphs - Tools to extract information from graphs interactively Basic Plotting Commands - Plotting vector and matrix data in 2-D representations Creating Specialized Plots - Creating bar graphs, histograms, contour plots, and other specialized plots Printing and Exporting - Printing graphs on paper and exporting graphs to standard graphic file formats Handle Graphics Objects - MATLAB graphics objects and properties
2
Overview MATLAB provides a wide variety of techniques to display data graphically. Plottools Plotting commands – line, bar, histogram, … Edit graph by modifying the properties of graph objects Interactive tools enable you to manipulate graphs to achieve results that reveal the most information about your data. You can also annotate and print graphs for presentations, or export graphs to standard graphics formats for presentation in web browsers or other media.
3
Creating a graph Plot sin(x) Plotting tools Command interface
x = 0:pi/100:2*pi; y = sin(x); plot(x,y) label the axes and add a title xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function','FontSize',12)
4
Multiple Data Sets in One Graph
For example, these statements plot three related functions of x, with each curve in a separate distinguishing color: Add legend x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3) legend('sin(x)','sin(x-.25)','sin(x-.5)')
5
Plotting Lines and Markers
If you specify a marker type but not a line style, MATLAB draws only the marker. For example, plot(x,y,'ks') plots black squares at each data point, but does not connect the markers with a line. The statement plot(x,y,'r:+') plots a red dotted line and places plus sign markers at each data point. x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
6
Adding Plots to an Existing Graph
The hold command enables you to add plots to an existing graph. [x,y,z] = peaks; pcolor(x,y,z) shading interp hold on contour(x,y,z,20,'k') hold off
7
Axis Labels and Titles The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure The text function inserts text anywhere in the figure. You can produce mathematical symbols using LaTeX notation t = -pi:pi/100:pi; y = sin(t); plot(t,y) axis([-pi pi -1 1]) xlabel('-\pi \leq {\itt} \leq \pi') ylabel('sin(t)') title('Graph of the sine function') text(1,-1/3,'{\itNote the odd symmetry.}')
8
Mesh and Surface Plots The mesh and surf plotting functions display surfaces in three dimensions. mesh produces wireframe surfaces that color only the lines connecting the defining points. surf displays both the connecting lines and the faces of the surface in color. To display a function of two variables, z = f (x,y), Generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. Use X and Y to evaluate and graph the function. The meshgrid function transforms the domain specified by a single vector or two vectors x and y into matrices X and Y for use in evaluating functions of two variables. The rows of X are copies of the vector x and the columns of Y are copies of the vector y.
9
Example — Graphing the sinc Function
[X,Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + eps; Z = sin(R)./R; mesh(X,Y,Z,'EdgeColor','black')
10
Example — Colored Surface Plots
[X,Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + eps; Z = sin(R)./R; surf(X,Y,Z) colormap hsv colorbar
11
Example — Surface Plots with Lighting
[X,Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + eps; Z = sin(R)./R; surf(X,Y,Z,'FaceColor','red','EdgeColor','none') camlight left; lighting phong
12
Printing & Exporting Graphics
Use the Print or Export Setup options under the File menu Save As under the File menu Use the print command to print or export the figure For example, this statement saves the contents of the current figure window as color Encapsulated Level 2 PostScript in the file called magicsquare.eps. It also includes a TIFF preview, which enables most word processors to display the picture: print -depsc2 -tiff magicsquare.eps To save the same figure as a TIFF file with a resolution of 200 dpi, use the command print -dtiff -r200 magicsquare.tiff
13
Handle Graphics Handle Graphics refers to a system of graphics objects that MATLAB uses to implement graphing and visualization functions. Each object created has a fixed set of properties. You can use these properties to control the behavior and appearance of your graph. x = 1:10; y = x.^3; h = plot(x,y); set(h,'Color','red') When you query the lineseries properties, get(h,'LineWidth') Use the handle to see what properties a particular object contains: get(h)
14
Graphics Objects
15
Key Graphics Objects Lineseries plot objects — Represent the data passed to the plot function Axes — Provide a frame of reference and scaling for the plotted lineseries Text — Label the axes tick marks and are used for titles and annotations Figures — Are the windows that contain axes toolbars, menus, etc.
16
Commands for Working with Objects
gca Return the handle of the current axes gcf Return the handle of the current figure gco Return the handle of the current object get Query the values of an object's properties set Set the values of an object's properties allchild Find all children of specified objects cncestor Find ancestor of graphics object copyobj Copy graphics object delete Delete an object findall Find all graphics objects (including hidden handles)
17
Specifying the Axes or Figure
y = [1.5*cos(x) + 6*exp(-.1*x) + exp(.07*x).*sin(3*x)]; ym = mean(y); hfig = figure('Name','Function and Mean',... 'Pointer','fullcrosshair'); hax = axes('Parent',hfig); plot(hax,x,y) hold on plot(hax,[min(x) max(x)],[ym ym],'Color','red') hold off ylab = get(hax,'YTick'); set(hax,'YTick',sort([ylab ym])) title ('y = 1.5cos(x) + 6e^{-0.1x} + e^{0.07x}sin(3x)') xlabel('X Axis'); ylabel('Y Axis')
18
Specifying the Axes or Figure
y = [1.5*cos(x) + 6*exp(-.1*x) + exp(.07*x).*sin(3*x)]; ym = mean(y); hfig = figure('Name','Function and Mean',... 'Pointer','fullcrosshair'); hax = axes('Parent',hfig); plot(hax,x,y) hold on plot(hax,[min(x) max(x)],[ym ym],'Color','red') hold off ylab = get(hax,'YTick'); set(hax,'YTick',sort([ylab ym])) title ('y = 1.5cos(x) + 6e^{-0.1x} + e^{0.07x}sin(3x)') xlabel('X Axis'); ylabel('Y Axis')
19
Animations Erase Mode Method — Continually erase and then redraw the objects on the screen, making incremental changes with each redraw. Creating Movies — Save a number of different pictures and then play them back as a movie. Using AVI files. See avi-file for more information and examples.
20
Erase Mode Method n = 20; s = .02;
x = rand(n,1)-0.5; y = rand(n,1)-0.5; h = plot(x,y,'.'); axis([ ]) axis square grid off set(h,'EraseMode','xor','MarkerSize',18) while 1 drawnow x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,'XData',x,'YData',y) end
21
Creating Movies figure('position',[100 100 850 600])
Z = peaks; surf(Z); axis tight set(gca,'nextplot','replacechildren'); % Record the movie for j = 1:20 surf(sin(2*pi*j/20)*Z,Z) F(j) = getframe; end [h, w, p] = size(F(1).cdata); hf = figure; % resize figure based on frame's w x h, and place at(150,150) set(hf, 'position', [ w h]); axis off % tell movie command to place frames at bottom left movie(hf,F,4,30,[ ]);
22
Annotation Objects annotation('line',x,y) annotation('arrow',x,y) annotation('doublearrow',x,y) annotation('textarrow',x,y) annotation('textbox',[x y w h]) annotation('ellipse',[x y w h]) annotation('rectangle',[x y w h]) annotation(figure_handle,...) annotation(...,'PropertyName',PropertyValue,...) anno_obj_handle = annotation(...)
23
Graphics 2D Elementary X-Y graphs. plot - Linear plot.
loglog Log-log scale plot. semilogx - Semi-log scale plot. semilogy - Semi-log scale plot. polar Polar coordinate plot. plotyy Graphs with y tick labels on the left and right. Annotation texlabel - Produces the TeX format from a character string. text Text annotation. gtext Place text with mouse.
24
Graphics 3D Elementary 3-D plots.
plot3 - Plot lines and points in 3-D space. mesh D mesh surface. surf D colored surface. fill Filled 3-D polygons. Color control. colormap - Color look-up table. caxis Pseudocolor axis scaling. shading - Color shading mode. hidden Mesh hidden line removal mode. brighten - Brighten or darken color map. colordef - Set color defaults.
25
Specialized graphs: Specialized 2-D graphs. area - Filled area plot.
bar Bar graph. barh Horizontal bar graph. comet Comet-like trajectory. compass Compass plot. errorbar Error bar plot. ezplot Easy to use function plotter. ezpolar Easy to use polar coordinate plotter. feather Feather plot. fill Filled 2-D polygons. fplot Plot function. hist Histogram. pareto Pareto chart. pie Pie chart. plotmatrix - Scatter plot matrix. rose Angle histogram plot. scatter Scatter plot. stem Discrete sequence or "stem" plot. stairs Stairstep plot. Contour and 2-1/2 D graphs. contour Contour plot. contourf Filled contour plot. contour D Contour plot. clabel Contour plot elevation labels. ezcontour - Easy to use contour plotter. ezcontourf - Easy to use filled contour plotter. pcolor Pseudocolor (checkerboard) plot. voronoi Voronoi diagram. Specialized 3-D graphs. bar D bar graph. bar3h Horizontal 3-D bar graph. comet D comet-like trajectories. ezgraph General purpose surface plotter. ezmesh Easy to use 3-D mesh plotter. ezmeshc Easy to use combination mesh/contour plotter. ezplot Easy to use 3-D parametric curve plotter. ezsurf Easy to use 3-D colored surface plotter. ezsurfc Easy to use combination surf/contour plotter. meshc Combination mesh/contour plot. meshz D mesh with curtain. pie D pie chart. ribbon Draw 2-D lines as ribbons in 3-D. scatter D scatter plot. stem D stem plot. surfc Combination surf/contour plot. trisurf Triangular surface plot. trimesh Triangular mesh plot. waterfall - Waterfall plot. Volume and vector visualization. vissuite Visualization suite. isosurface - Isosurface extractor. isonormals - Isosurface normals. isocaps Isosurface end caps. isocolors - Isosurface and patch colors. contourslice - Contours in slice planes. slice Volumetric slice plot. streamline - Streamlines from 2D or 3D vector data. stream D streamlines. stream D streamlines. quiver D quiver plot. quiver D quiver plot. divergence - Divergence of a vector field. curl Curl and angular velocity of a vector field. coneplot D cone plot. streamtube - 3D stream tube. streamribbon - 3D stream ribbon. streamslice - Streamlines in slice planes. streamparticles - Display stream particles. interpstreamspeed - Interpolate streamline vertices from speed. subvolume - Extract subset of volume dataset. reducevolume - Reduce volume dataset. volumebounds - Returns x,y,z and color limits for volume data. smooth Smooth 3D data. reducepatch - Reduce number of patch faces. shrinkfaces - Reduce size of patch faces. Images display and file I/O. image Display image. imagesc Scale data and display as image. colormap Color look-up table. gray Linear gray-scale color map. contrast Gray scale color map to enhance image contrast. brighten Brighten or darken color map. colorbar Display color bar (color scale). imread Read image from graphics file. imwrite Write image to graphics file. imfinfo Information about graphics file. im2java Convert image to Java image. Movies and animation. getframe Get movie frame. movie Play recorded movie frames. rotate Rotate object about specified orgin and direction. frame2im Convert movie frame to indexed image. im2frame Convert index image into movie format. Color related functions. spinmap Spin color map. rgbplot Plot color map. colstyle Parse color and style from string. ind2rgb Convert indexed image to RGB image. Solid modeling. cylinder Generate cylinder. sphere Generate sphere. ellipsoid - Generate ellipsoid. patch Create patch. surf2patch - Convert surface data to patch data.
26
How to draw this graph? Ma etc. Genetics, Vol. 161, , 2002
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.