MATLAB (2): Graphics

Embed Size (px)

Citation preview

  • 8/12/2019 MATLAB (2): Graphics

    1/45

    MATLABGraphics

  • 8/12/2019 MATLAB (2): Graphics

    2/45

    Basic Plotting Commands

    figure : creates a new figure windowplot(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 specifiedin string : 'r' = red, 'g'=green, etc

    for a limited set of basic colours.

    '' solid line, '' dashed, 'o'circlessee graphics section ofhelpdesk

  • 8/12/2019 MATLAB (2): Graphics

    3/45

    >> plot(glon,glat)>> xlabel('Longitude'),ylabel('Latitude')>> title('Flight Track : CW96 960607')

  • 8/12/2019 MATLAB (2): Graphics

    4/45

    >> plot3(glon,glat,palt,'linewidth',2)>> grid>> xlabel('Longitude'),ylabel('Latitude')>> zlabel('Altitude (m)')

  • 8/12/2019 MATLAB (2): Graphics

    5/45

    Subplots

    subplot(m,n,p): create a subplot in an array of axes

    >> subplot(2,3,1);

    >> subplot(2,3,4);

    m

    n

    P=1 P=2 P=3

    P=4

  • 8/12/2019 MATLAB (2): Graphics

    6/45

    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 Cand vector of handles to

    to contours, h.

  • 8/12/2019 MATLAB (2): Graphics

    7/45

    contourf(Z) : plot contours filled withcolour

    clabel(C,h) : add labels to contours

    clabel(C,h,v) : add labels only atcontours specified in v

    clabel(C,h,'manual')

    : add labels to contours atlocations selected with

    mouse

  • 8/12/2019 MATLAB (2): Graphics

    8/45

    >> peaks;

    Peaks is an example function, useful for demonstrating 3D

    data, contouring, etc. Figure above is its default output.

    P=peaks;- return data matrix for replotting

  • 8/12/2019 MATLAB (2): Graphics

    9/45

    >> P = peaks;>> contour(P)

  • 8/12/2019 MATLAB (2): Graphics

    10/45

    >> contour(P,[-9:0.5:9])

  • 8/12/2019 MATLAB (2): Graphics

    11/45

  • 8/12/2019 MATLAB (2): Graphics

    12/45

    >> contourf(P,[-9:0.5:9]);>> colorbar

  • 8/12/2019 MATLAB (2): Graphics

    13/45

    Pseudocolour plots

    An alternative to contouringprovides acontinuous colour-mapped 2D 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

  • 8/12/2019 MATLAB (2): Graphics

    14/45

    >> pcolor(P) >> shading flat

    >> shading interpData points are at vertices of grid,

    colour of facet indicates mean value of

    vertices. Colours are selected by

    interpolating data range into acolormap

  • 8/12/2019 MATLAB (2): Graphics

    15/45

    >> pcolor(P);shading flat>> hold on>> contour(P,[1:9],'k')>> contour(P,[-9:-1],'k--')

    >> contour(P,[0 0],'k','linewidth',2)>> colorbar

  • 8/12/2019 MATLAB (2): Graphics

    16/45

    colormaps

    Surfaces are coloured by scaling the data rangeto 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

    >> colormapmapname

    >> colormap('mapname') The current colormap can be retrieved with

    >> map=colormap

  • 8/12/2019 MATLAB (2): Graphics

    17/45

    >> colormap cool

  • 8/12/2019 MATLAB (2): Graphics

    18/45

    >> caxis([0 8])>> colorbar

  • 8/12/2019 MATLAB (2): Graphics

    19/45

  • 8/12/2019 MATLAB (2): Graphics

    20/45

    Handle Graphics

    MATLAB uses a hierarchical graphics model Graphics objects organised according to theirdependencies: e.g. linesmust be plotted on axes,

    axesmust 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

  • 8/12/2019 MATLAB (2): Graphics

    21/45

    root

    figure

    axes UI-control UI-menu UI-contextmenu

    line light image patch surface rectangle text

    Object Hierarchy

  • 8/12/2019 MATLAB (2): Graphics

    22/45

    Each graphics object has properties that can bemodified, e.g. for a line object: colour, width, linestyle, marker style, stacking order on plot,

    Many properties can be modified via the figurewindow. Tools available depend upon theversion runninggreatly expanded in version 7.

    More useful to use command linemuch faster,and can be included in scripts or functions toautomate whole process.

  • 8/12/2019 MATLAB (2): Graphics

    23/45

    Object selectAdd/edit text

    Add arrow & linezoom

    3D rotate

  • 8/12/2019 MATLAB (2): Graphics

    24/45

    Properties of an object with handle H, can beinspected/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 figurereturns handle of current figure

    gca: get current axesreturns handle of current axes

    gco: get current objectreturns handle of current object

    Can use these directly, instead of the handle

  • 8/12/2019 MATLAB (2): Graphics

    25/45

    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 (x0, y0), 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.

  • 8/12/2019 MATLAB (2): Graphics

    26/45

    x0

    y0

    dx

    dy

    Figure's 'position' on screen is [x0y0dx dy]

    (default units are pixels)

    axis 'position' within thefigure: (default units are

    'normalized')

  • 8/12/2019 MATLAB (2): Graphics

    27/45

    A4 page

    Figure's default position on

    the page: it's 'paperposition'

    (default 'paperunits' are'centimeters')

    axis position within the

    figure: it's 'position'

    (default units are'normalized')

  • 8/12/2019 MATLAB (2): Graphics

    28/45

    Parameter value pairs

    Many basic plotting commands accept

    parameter-value pairs to specify plottingcharacteristics:

    plot(x,y,'para1',value1,'para2',value2,)

    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)

  • 8/12/2019 MATLAB (2): Graphics

    29/45

    Adding Text to Figures

    Basic axis labels and title can be added viaconvenient functions:>> xlabel('x-axis label text')

    >> ylabel('y-axis label text')

    >> title('title text')

    Legends for line or symbol types are added via

    the legendfunction:>> legend('line 1 caption','line 2 caption',)

    >> legend([h1,h2,],'caption 1','caption 2',)

  • 8/12/2019 MATLAB (2): Graphics

    30/45

    >> subplot(1,2,1)>> plot(theta(eval(sw1_2)),palt(eval(sw1_2)),'r');hold on>> plot(theta(eval(sw1_7)),palt(eval(sw1_7)),'g')>> xlabel('\theta (K)'); ylabel('Altitude (m)')

  • 8/12/2019 MATLAB (2): Graphics

    31/45

    >> hh(1)=plot(xwsc(eval(sw1_2)),palt(eval(sw1_2)),'r');>> hold on>> hh(2)=plot(xwsc(eval(sw1_7)),palt(eval(sw1_7)),'g');>> hh(3)=plot(xwsc(eval(sw1_5)),palt(eval(sw1_5)),'b');

    >> xlabel('windspeed (m s^{-1})');>> set(gca,'yticklabel',[])>> legend(hh([1 3 2]),'sw2','sw5','sw7')

  • 8/12/2019 MATLAB (2): Graphics

    32/45

    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 thespecified location (in data coordinateslocations

    outside the current axes limits are OK)

    >> gtext('text to add')adds text at a location

    selected with the cursor

  • 8/12/2019 MATLAB (2): Graphics

    33/45

    Obtaining Values from a Figure

    The ginputfunction returns values from cursor-

    selected points on a graph.

    >> [x,y] = ginput(n) selects n values

    >> [x,y] = ginput selects values until

    'return' key is pressed

    NB. ginputworks on the current axes, and will return

    values outside visible axis data range if points outside

    axis frame are selected.

  • 8/12/2019 MATLAB (2): Graphics

    34/45

    Printing Figures

    At its simplest, the command

    >> print

    sends the current figure to the default printer.

    >> print fn

    prints figure number nto the default printer

    Under unix, a command line switch may be used

    to specify a printer:

    >> print Pprinter

  • 8/12/2019 MATLAB (2): Graphics

    35/45

  • 8/12/2019 MATLAB (2): Graphics

    36/45

  • 8/12/2019 MATLAB (2): Graphics

    37/45

    .png .jpg

  • 8/12/2019 MATLAB (2): Graphics

    38/45

    Saving a MATLAB figure

    The functions hgsaveand hgloadsave and

    load a figure to a .figfilethis 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 thefigure are NOT saved.

    >> hgsave(gcf,'filename')

    >> hgload('filename.fig')

  • 8/12/2019 MATLAB (2): Graphics

    39/45

    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 5km intervals

    along the flight legs.

  • 8/12/2019 MATLAB (2): Graphics

    40/45

    >> load /cw96/jun07/jun07_all_5km_means.mat>> whoYour variables are:mQ mlat mlon msst mtheta mthetav mu mvmws

    >> plot(mlon,mlat,'o')>> print -dpng -r100 figures/grid-1-data-points

  • 8/12/2019 MATLAB (2): Graphics

    41/45

    >> [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>> h1=plot(mlon,mlat,'ko');>> print -dpng -r100 figures/grid-2-wind-field

  • 8/12/2019 MATLAB (2): Graphics

    42/45

    ( 2 )

  • 8/12/2019 MATLAB (2): Graphics

    43/45

    >> 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('CW96 : June 07 : 30m wind field')

    >> load mendocinopatch.mat>> patch(mendocinopatch(:,1),mendocinopatch(:,2),[0.9 0.9 0.9])>> print -dpng -r100 figures/grid-4-wind-field-and-vectors-and-coast

  • 8/12/2019 MATLAB (2): Graphics

    44/45

    % 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:33data1=Q012D_K3{n};data2=Q012D_I50{n}(iz,:);surf(X,Y,ZH,data1);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,data2);shading flat;set(gca,'zlim',[0 max(Z(iz))])Qframes(n-3)=getframe; % NB first n=4, force frames index tohold off % start at 1 to avoid empty frames

    End

    % play movie in matlab

    axis([0 1 0 1 0 1])set(gca,'visible','off')movie(Qframes,5)

    % save movie to AVI filemovie2avi(Qframes,'testavi.avi','compression','none')

  • 8/12/2019 MATLAB (2): Graphics

    45/45