db6c9eb60111aa0a60abe46f2dc5d2e8.ppt
- Количество слайдов: 45
MATLAB Graphics
Basic Plotting Commands • figure : creates a new figure window • plot(x) : plots line graph of x vs index number of array • plot(x, y) : plots line graph of x vs y • plot(x, y, 'r--') : plots x vs y with linetype specified in string : 'r' = red, 'g'=green, etc for a limited set of basic colours. ' ' solid line, ' ' dashed, 'o' circles…see graphics section of helpdesk
>> plot(glon, glat) >> xlabel('Longitude'), ylabel('Latitude') >> title('Flight Track : CW 96 960607')
>> >> plot 3(glon, glat, palt, 'linewidth', 2) grid xlabel('Longitude'), ylabel('Latitude') zlabel('Altitude (m)')
Subplots • subplot(m, n, p) : create a subplot in an array of axes >> subplot(2, 3, 1); P=1 P=2 P=3 >> subplot(2, 3, 4); m P=4 n
Contour plots • contour(Z) : plot contours of matrix Z • contour(Z, n) : plot n contours (n = integer) • contour(Z, v) : plot contours at levels specified in vector v • contour(X, Y, Z) : plot contours of matrix Z on grid specified by X and Y • [C, h]=contour(…): returns contour matrix C and vector of handles to to contours, h.
• contourf(Z) : plot contours filled with colour : add labels to contours : add labels only at contours specified in v • clabel(C, h, 'manual') : add labels to contours at locations selected with mouse • clabel(C, h) • clabel(C, h, v)
>> peaks; Peaks is an example function, useful for demonstrating 3 D data, contouring, etc. Figure above is its default output. P=peaks; - return data matrix for replotting…
>> P = peaks; >> contour(P)
>> contour(P, [-9: 0. 5: 9])
>> [C, h]=contour(P); >> clabel(C, h);
>> contourf(P, [-9: 0. 5: 9]); >> colorbar
Pseudocolour plots An alternative to contouring – provides a continuous colour-mapped 2 D data field • pcolor(Z) : plot pseudocolour plot of Z • pcolor(X, Y, Z) : plot of Z on grid X, Y • shading faceted | flat | interp : set shading option – faceted : show edge lines (default) – flat : don't show edge lines – interp : colour is linearly interpolated to give smooth variation
>> pcolor(P) Data points are at vertices of grid, colour of facet indicates mean value of vertices. Colours are selected by interpolating data range into a colormap >> shading flat >> shading interp
>> >> >> pcolor(P); shading flat hold on contour(P, [1: 9], 'k') contour(P, [-9: -1], 'k--') contour(P, [0 0], 'k', 'linewidth', 2) colorbar
colormaps • Surfaces are coloured by scaling the data range to the current colormap. A colormap applies to a whole figure. • Several predefined colormaps exist ('jet' (the default), 'warm', 'cool', 'copper', 'bone', 'hsv'). Select one with >> colormap mapname >> colormap('mapname') • The current colormap can be retrieved with >> map=colormap
>> colormap cool
>> caxis([0 8]) >> colorbar
• Colormaps are simply 3 -column matrices of arbitrary length (default = 64 rows). Each row contains the [RED GREEN BLUE] components of the colour required, specified on a 0 1 scale. e. g. >> mymap = [ 0 0 0. 1 0. 2 0. 3. . . ] >> colormap(mymap)
Handle Graphics • MATLAB uses a hierarchical graphics model – Graphics objects organised according to their dependencies: e. g. lines must be plotted on axes, axes must be positioned on figures – Every object has a unique identifier, or handle • Handles are returned by creating function – ax(n)=subplot(3, 2, n) – h=plot(x, y) • Handles can be used to identify an object in order to inspect (get) or modify (set) its properties at any time
Object Hierarchy root figure axes line UI-control light image UI-menu patch UI-contextmenu surface rectangle text
• Each graphics object has properties that can be modified, e. g. for a line object: colour, width, line style, marker style, stacking order on plot, … • Many properties can be modified via the figure window. Tools available depend upon the version running – greatly expanded in version 7. • More useful to use command line – much faster, and can be included in scripts or functions to automate whole process.
Object select Add/edit text Add arrow & line zoom 3 D rotate
• Properties of an object with handle H, can be inspected/modified by: >> value = get(H, 'propertyname') >> set(H, 'propertyname', value) • All property values echoed to screen by: >> get(H) • 3 useful functions: – gcf : get current figure – returns handle of current figure – gca : get current axes – returns handle of current axes – gco : get current object – returns handle of current object Can use these directly, instead of the handle
• Current object is last created (usually), or last object clicked on with mouse. >> pp = get(gca, 'position') pp = 0. 1300 0. 1100 0. 7750 0. 8150 >> set(gca, 'position', pp+[0 0. 1 0 -0. 1]) The code above first gets the position of the current axes – location of bottom left corner (x 0, y 0), width (dx) and height (dy) (in normalised units) – then resets the position so that the axes sit 0. 1 units higher on the page and decreases their height by 0. 1 units.
dy axis 'position' within the figure: (default units are 'normalized') dx x 0 y 0 Figure's 'position' on screen is [x 0 y 0 dx dy] (default units are pixels)
axis position within the figure: it's 'position' (default units are 'normalized') Figure's default position on the page: it's 'paperposition' (default 'paperunits' are 'centimeters') A 4 page
Parameter value pairs • Many basic plotting commands accept parameter-value pairs to specify plotting characteristics: – plot(x, y, 'para 1', value 1, 'para 2', value 2, …) • Commonly used parameters : values – 'linewidth': in points, numeric (default =0. 5) – 'color' : 'r', 'g', 'b', 'c', 'k', 'm', 'y' – basic colours (strings) : [R, G, B] – red, green, blue components. Range from 0 to 1 (0 to 100%), eg [0, 0. 5, 1] – 'marker' : shape of marker/symbol to plot '. ' point, 'v' triangle, '^' triangle(up pointing), … – 'markeredgecolor', 'markerfacecolor' : edge and body colours of plotting symbols – 'markersize' : marker size in points (default = 6)
Adding Text to Figures • Basic axis labels and title can be added via convenient functions: >> xlabel('x-axis label text') >> ylabel('y-axis label text') >> title('title text') • Legends for line or symbol types are added via the legend function: >> legend('line 1 caption', 'line 2 caption', …) >> legend([h 1, h 2, …], 'caption 1', 'caption 2', …)
>> >> subplot(1, 2, 1) plot(theta(eval(sw 1_2)), palt(eval(sw 1_2)), 'r'); hold on plot(theta(eval(sw 1_7)), palt(eval(sw 1_7)), 'g') xlabel('theta (K)'); ylabel('Altitude (m)')
>> >> hh(1)=plot(xwsc(eval(sw 1_2)), palt(eval(sw 1_2)), 'r'); hold on hh(2)=plot(xwsc(eval(sw 1_7)), palt(eval(sw 1_7)), 'g'); hh(3)=plot(xwsc(eval(sw 1_5)), palt(eval(sw 1_5)), 'b'); xlabel('windspeed (m s^{-1})'); set(gca, 'yticklabel', []) legend(hh([1 3 2]), 'sw 2', 'sw 5', 'sw 7')
• MATLAB uses a subset of TEX commands for mathematical symbols, greek characters etc. • Text may be added at any location via the commands: >> text(x, y, 'text to add') – adds text at the specified location (in data coordinates – locations outside the current axes limits are OK) >> gtext('text to add') – adds text at a location selected with the cursor
Obtaining Values from a Figure • The ginput function returns values from cursorselected points on a graph. >> [x, y] = ginput(n) >> [x, y] = ginput – selects n values – selects values until 'return' key is pressed NB. ginput works on the current axes, and will return values outside visible axis data range if points outside axis frame are selected.
Printing Figures • At its simplest, the command >> print sends the current figure to the default printer. >> print –fn prints figure number n to the default printer • Under unix, a command line switch may be used to specify a printer: >> print –Pprinter
Printing to Files • A wide variety of file formats are supported for printing; the general form is: >> print –driver –options filename e. g. >> print –dps filename print postscript file >> print –dpsc filename print colour postscript file >> print –depsc filename print colour encapsulated postscript file
>> print –djpeg filename print JPEG file (a BAD file format for almost any figure) >> print –dpng –r 200 filename print PNG file at 200 dpi. All bit-mapped file formats accept a –rnnn option to specify print resolution (default is 150 dpi)
. png . jpg
Saving a MATLAB figure • The functions hgsave and hgload save and load a figure to a. fig file – this contains the complete MATLAb handle graphics description of the figure, which can then be modified at a later date. NB the variables used to create the figure are NOT saved. >> hgsave(gcf, 'filename') >> hgload('filename. fig')
Putting it all together… • The following slides show the development of a moderately complex figure from raw data : near-surface aircraft measurements of basic meteorology averaged down to 5 km intervals along the flight legs.
>> load /cw 96/jun 07_all_5 km_means. mat >> who Your variables are: m. Q mlat mlon msst mtheta mws mthetav >> plot(mlon, mlat, 'o') >> print -dpng -r 100 figures/grid-1 -data-points mu mv
>> >> [XX, YY]=meshgrid([-125. 2: 0. 05: -124], [39. 9: 0. 05: 40. 8]); gmws=griddata(mlon, mlat, mws, XX, YY); pcolor(XX, YY, gmws); shading flat; hbar=colorbar; hold on h 1=plot(mlon, mlat, 'ko'); print -dpng -r 100 figures/grid-2 -wind-field
>> >> >> gu=griddata(mlon, mlat, mu, XX, YY); gv=griddata(mlon, mlat, mv, XX, YY); quiver(XX, YY, gu, gv, 'k-'); set(h 1, 'markeredgecolor', 'markersize', 5) print -dpng -r 100 figures/grid-3 -wind-field-and-vectors
>> >> >> set(gca, 'linewidth', 2, 'fontweight', 'bold') xlabel('Longitude'); ylabel('latitude') set(hbar, 'linewidth', 2, 'fontweight', 'bold') set(get(hbar, 'xlabel'), 'string', '(m s^{-1})', 'fontweight', 'bold') xlabel('Longitude'); ylabel('latitude') title('CW 96 : June 07 : 30 m wind field') load mendocinopatch. mat patch(mendocinopatch(: , 1), mendocinopatch(: , 2), [0. 9]) print -dpng -r 100 figures/grid-4 -wind-field-and-vectors-and-coast
% generate movie frames from LEM fields [XX, ZZ]=meshgrid(X, Z(iz)); [YY, ZZ]=meshgrid(Y*0, Z(iz)); ZH=ones([102 102])*Z(3); for n=4: 33 data 1=Q 012 D_K 3{n}; data 2=Q 012 D_I 50{n}(iz, : ); surf(X, Y, ZH, data 1); shading flat; set(gca, 'xticklabel', {}, 'yticklabel', {}, 'zticklabel', {}); set(gca, 'xlim', [min(X) max(X)], 'ylim', [min(Y) max(Y)]) hold on surf(XX, YY, ZZ, data 2); shading flat; set(gca, 'zlim', [0 max(Z(iz))]) Qframes(n-3)=getframe; % NB first n=4, force frames index to hold off % start at 1 to avoid empty frames End % play movie in matlab axis([0 1 0 1]) set(gca, 'visible', 'off') movie(Qframes, 5) % save movie to AVI file movie 2 avi(Qframes, 'testavi. avi', 'compression', 'none')
db6c9eb60111aa0a60abe46f2dc5d2e8.ppt