source: trunk/src/plot_field.m @ 106

Last change on this file since 106 was 105, checked in by sommeria, 14 years ago

Bug fix

File size: 49.5 KB
Line 
1%'plot_field': plot any field with the structure defined in the uvmat package
2%------------------------------------------------------------------------
3%
4%  This function is used by uvmat to plot fields. It automatically chooses the representation
5% appropriate to the input field structure:
6%     2D vector fields are represented by arrows, 2D scalar fiedlds by grey scale images or contour plots, 1D fields are represented by usual plot with (abscissa, ordinate).
7%  The input field structure is first tested by check_field_structure.m,
8%  then split into blocks of related variables  by find_field_indices.m.
9%  The dimensionality of each block is obtained  by this fuction
10%  considering the presence of variables with the attribute .Role='coord_x'
11%  and/or coord_y and/or coord_z (case of unstructured coordinates), or
12%  dimension variables (case of matrices).
13%
14% function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,htext,PosColorbar)
15%
16% OUPUT:
17% PlotType: type of plot: 'text','line'(curve plot),'plane':2D view,'volume'
18% PlotParamOut: structure, representing the updated  plotting parameters, in case of automatic scaling
19% haxes: handle of the plotting axis, when a new figure is created.
20%
21%INPUT
22%    Data:   structure describing the field to plot
23%         (optional) .ListGlobalAttribute: cell listing the names of the global attributes
24%                    .Att_1,Att_2... : values of the global attributes
25%         (requested)  .ListVarName: list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
26%         (requested)  .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)
27%                      .VarAttribute: cell of attributes for each element of .ListVarName (cell array of structures of the form VarAtt.key=value)
28%         (requested) .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
29
30%            Variable attribute .Role :
31%    The only variable attribute used for plotting purpose is .Role which can take
32%    the values
33%       Role = 'scalar':  (default) represents a scalar field
34%            = 'coord_x', 'coord_y',  'coord_z': represents a separate set of
35%                        unstructured coordinate x, y  or z
36%            = 'vector': represents a vector field whose number of components
37%                is given by the last dimension (called 'nb_dim')
38%            = 'vector_x', 'vector_y', 'vector_z'  :represents the x, y or z  component of a vector 
39%            = 'warnflag' : provides a warning flag about the quality of data in a 'Field', default=0, no warning
40%            = 'errorflag': provides an error flag marking false data,
41%                   default=0, no error. Different non zero values can represent different criteria of elimination.
42%
43%
44%         additional elements characterizing the projection object (should not be necessary)--
45%            Data.Style : style of projection object
46%            Data.XObject,.YObject: set of coordinates defining the object position;
47%            Data.ProjMode=type of projection ;
48%            Data.ProjAngle=angle of projection;
49%            Data.DX,.DY,.DZ=increments;
50%            Data.MaxY,MinY: min and max Y
51
52%   haxes: handle of the plotting axes to update with the new plot. If this input is absent or not a valid axes handle, a new figure is created.
53%
54%   PlotParam: parameters for plotting, as read on the uvmat interface (by function 'read_plot_param.m')
55%     .FixedLimits:=0 (default) adjust axes limit to the X,Y data, =1: preserves the previous axes limits
56%     .Auto_xy: =0 (default): kepp 1 to 1 aspect ratio for x and y scales, =1: automatic adjustment of the graph
57%            --scalars--
58%    .Scalar.MaxA: upper bound (saturation color) for the scalar representation, max(field) by default
59%    .Scalar.MinA: lower bound (saturation) for the scalar representation, min(field) by default
60%    .Scalar.AutoScal: =1 (default) lower and upper bounds of the scalar representation set to the min and max of the field
61%               =0 lower and upper bound imposed by .AMax and .MinA
62%    .Scalar.BW= 1 black and white representation imposed, =0 by default.
63%    .Scalar.Contours= 1: represent scalars by contour plots (Matlab function 'contour'); =0 by default
64%    .IncrA : contour interval
65%            -- vectors--
66%    .Vectors.VecScale: scale for the vector representation
67%    .Vectors.AutoVec: =0 (default) automatic length for vector representation, =1: length set by .VecScale
68%    .Vectors.HideFalse= 0 (default) false vectors represented in magenta, =1: false vectors not represented;
69%    .Vectors.HideWarning= 0 (default) vectors marked by warnflag~=0 marked in black, 1: no warning representation;
70%    .Vectors.decimate4 = 0 (default) all vectors reprtesented, =1: half of  the vectors represented along each coordinate
71%         -- vector color--
72%    .Vectors.ColorCode= 'black','white': imposed color  (default ='blue')
73%                        'rgb', : three colors red, blue, green depending
74%                        on thresholds .colcode1 and .colcode2 on the input  scalar value (C)
75%                        'brg': like rgb but reversed color order (blue, green, red)
76%                        '64 colors': continuous color from blue to red (multijet)
77%    .Vectors.colcode1 : first threshold for rgb, first value for'continuous'
78%    .Vectors.colcode2 : second threshold for rgb, last value (saturation) for 'continuous'
79%    .Vectors.FixedCbounds;  =0 (default): the bounds on C representation are min and max, =1: they are fixed by .Minc and .MaxC
80%    .Vectors.MinC = imposed minimum of the scalar field used for vector color;
81%    .Vectors.MaxC = imposed maximum of the scalar field used for vector color;
82%
83%
84% PosColorbar: if not empty, display a colorbar for B&W images
85%               imposed position of the colorbar (ex [0.821 0.471 0.019 0.445])
86
87%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
88%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
89%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
90%     This file is part of the toolbox UVMAT.
91%
92%     UVMAT is free software; you can redistribute it and/or modify
93%     it under the terms of the GNU General Public License as published by
94%     the Free Software Foundation; either version 2 of the License, or
95%     (at your option) any later version.
96%
97%     UVMAT is distributed in the hope that it will be useful,
98%     but WITHOUT ANY WARRANTY; without even the implied warranty of
99%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
100%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
101%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
102
103function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,htext,PosColorbar)
104% TODO:
105% use htext: handles of the text edit box (uicontrol)
106% introduce PlotParam.Hold: 'on' or 'off' (for curves)
107 
108%default output
109if ~exist('PlotParam','var'),PlotParam=[];end;
110if ~exist('htext','var'),htext=[];end;
111if ~exist('PosColorbar','var'),PosColorbar=[];end;
112PlotType='text'; %default
113PlotParamOut=PlotParam;%default
114
115% check input structure
116[Data,errormsg]=check_field_structure(Data);
117
118if ~isempty(errormsg)
119    msgbox_uvmat('ERROR',['input of plot_field/check_field_structure: ' errormsg])
120    display(['input of plot_field/check_field_structure:: ' errormsg])
121    return
122end
123
124testnewfig=1;%test to create a new figure (default)
125testzoomaxes=0;%test for the existence of a zoom secondary figure attached to the plotting axes
126if exist('haxes','var')
127    if ishandle(haxes)
128        if isequal(get(haxes,'Type'),'axes')
129            axes(haxes)
130            testnewfig=0;
131            AxeData=get(haxes,'UserData');
132            if isfield(AxeData,'ZoomAxes')&& ishandle(AxeData.ZoomAxes)
133                if isequal(get(AxeData.ZoomAxes,'Type'),'axes')
134                    testzoomaxes=1;
135                    zoomaxes=AxeData.ZoomAxes;
136                end
137            end
138        end
139    end
140end
141if testnewfig% create a new figure and axes if the plotting axes does not exist
142    hfig=figure;
143%     if isfield(Data,'IndexObj') && isfield(Data,'Style') && isfield(Data,'ProjMode')
144%         figname=[num2str(Data.IndexObj) '-' Data.Style];
145%         set(hfig,'Name',figname)
146%     end
147%     testhandle=0;
148    if isfield(PlotParam,'text_display_1') && ishandle(PlotParam.text_display_1)
149        set(hfig,'UserData',PlotParam)
150%         testhandle=1;
151    end
152    set(hfig,'Units','normalized')
153    set(hfig,'WindowButtonDownFcn','mouse_down')
154    %set(hfig,'WindowButtonMotionFcn',{'mouse_motion',PlotParam})%set mouse action function
155    set(hfig,'WindowButtonMotionFcn','mouse_motion')%set mouse action function
156    set(hfig,'WindowButtonUpFcn','mouse_up')%set mouse action function
157    haxes=axes;
158    set(haxes,'position',[0.13,0.2,0.775,0.73])
159else
160    hstack=findobj(allchild(0),'Type','figure');%current stack order of figures in matlab
161end
162if isfield(PlotParam,'text_display_1') && ishandle(PlotParam.text_display_1)
163    PlotParam=read_plot_param(PlotParam);   
164end
165if testnewfig
166  PlotParam.NextPlot='add'; %parameter for plot_profile and plot_hist
167end
168if isfield(PlotParam,'Auto_xy') && isequal(PlotParam.Auto_xy,1)
169    set(haxes,'DataAspectRatioMode','auto')%automatic aspect ratio
170end
171
172% check the cells of fields :
173% testnbdim=1;
174[CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(Data);
175
176if ~isempty(errormsg)
177    msgbox_uvmat('ERROR',['input of plot_field/find_field_indices: ' errormsg])
178    display(['input of plot_field: ' errormsg])
179    return
180end
181if ~isfield(Data,'NbDim') %& ~isfield(Data,'Style')%determine the space dimensionb if not defined: choose the kind of plot
182    [Data.NbDim]=max(NbDim);
183end
184if isequal(Data.NbDim,0)
185        AxeData=plot_text(Data,htext);
186        PlotType='text';
187elseif isequal(Data.NbDim,1)
188    [AxeData,haxes]=plot_profile(Data,CellVarIndex,VarType,haxes,PlotParam);%
189    if testzoomaxes
190        [AxeData,zoomaxes,PlotParamOut]=plot_profile(Data,CellVarIndex,VarType,zoomaxes,PlotParam);
191        AxeData.ZoomAxes=zoomaxes;
192    end
193    PlotType='line';
194elseif isequal(Data.NbDim,2)
195    ind_select=find(NbDim>=2);
196    if numel(ind_select)>2
197        msgbox_uvmat('ERROR','more than two fields to map')
198        display('more than two fields to map')
199        return
200    end
201    [AxeData,haxes,PlotParamOut,PlotType]=plot_plane(Data,CellVarIndex(ind_select),VarType(ind_select),haxes,PlotParam,htext,PosColorbar);
202    if testzoomaxes
203        [AxeData,zoomaxes,PlotParamOut]=plot_plane(Data,CellVarIndex(ind_select),VarType(ind_select),zoomaxes,PlotParam,1,PosColorbar);
204        %AxeData.ZoomAxes=zoomaxes;
205        Data.ZoomAxes=zoomaxes;
206    end
207elseif isequal(Data.NbDim,3)
208    msgbox_uvmat('ERROR','volume plot not implemented yet')
209    return
210% else
211%     testnbdim=0;
212end
213
214%display (or delete) error message
215htext=findobj(haxes,'Tag','hTxt');
216if isfield(Data,'Txt')
217    if isempty(htext)
218        Xlim=get(haxes,'XLim');
219        Ylim=get(haxes,'YLim');
220        htext=text(Xlim(1),(Ylim(1)+Ylim(2))/2,Data.Txt,'Tag','hTxt','Color','r');
221        set(htext,'Interpreter','none')
222    else
223        set(htext,'String',Data.Txt)
224    end
225elseif ~isempty(htext)
226    delete(htext)
227end
228
229% set graph aspect ratio
230if isfield(AxeData,'Mesh')
231    Data.Mesh=AxeData.Mesh;
232end
233
234%set(haxes,'UserData',AxeData)
235set(haxes,'UserData',Data)
236if ~testnewfig
237set(0,'Children',hstack);%put back the initial figure stack after plot creation
238%set(haxes,'Tag','uvmat');
239end
240
241
242%-------------------------------------------------------------------
243function hdisplay=plot_text(FieldData,hdisplay_in)
244%-------------------------------------------------------------------
245hdisplay_in
246if exist('hdisplay_in','var') && ~isempty(hdisplay_in) && ishandle(hdisplay_in) && isequal(get(hdisplay_in,'Type'),'uicontrol')
247    hdisplay=hdisplay_in;
248else
249    figure;%create new figure
250    hdisplay=uicontrol('Style','edit', 'Units','normalized','Position', [0 0 1 1],'Max',2,'FontName','monospaced');
251end
252   
253ff=fields(FieldData);%list of field names
254vv=struct2cell(FieldData);%list of field values
255
256for icell=1:length(vv)
257    Tabcell{icell,1}=ff{icell};
258    ss=vv{icell};
259    sizss=size(ss);
260    if isnumeric(ss)
261        if sizss(1)<=1 && length(ss)<5
262            displ{icell}=num2str(ss);
263        else
264            displ{icell}=[class(ss) ', size ' num2str(size(ss))];
265        end
266    elseif ischar(ss)
267        displ{icell}=ss;
268    elseif iscell(ss)
269        sizcell=size(ss);
270        if sizcell(1)==1 && length(sizcell)==2 %line cell
271           ssline='{''';
272           for icolumn=1:sizcell(2)
273               if isnumeric(ss{icolumn})
274                   if size(ss{icolumn},1)<=1 && length(ss{icolumn})<5
275                      sscolumn=num2str(ss{icolumn});%line vector
276                   else
277                      sscolumn=[class(ss{icolumn}) ', size ' num2str(size(ss{icolumn}))];
278                   end
279               elseif ischar(ss{icolumn})
280                   sscolumn=ss{icolumn};
281               else
282                   sscolumn=class(ss{icolumn});
283               end
284               if icolumn==1
285                   ssline=[ssline sscolumn];
286               else
287                   ssline=[ssline ''',''' sscolumn];
288               end
289           end
290           displ{icell}=[ssline '''}'];
291        else
292           displ{icell}=[class(ss) ', size ' num2str(sizcell)];
293        end
294    else
295        displ{icell}=class(ss);
296    end
297    Tabcell{icell,2}=displ{icell};
298end
299Tabchar=cell2tab(Tabcell,': ');
300set(hdisplay,'String', Tabchar)
301
302
303%-------------------------------------------------------------------
304function [AxeData,haxes]=plot_profile(data,CellVarIndex,VarType,haxes,PlotParam)
305%-------------------------------------------------------------------
306%axes(haxes)
307hfig=get(haxes,'parent');
308AxeData=data;
309
310ColorOrder=[1 0 0;0 0.5 0;0 0 1;0 0.75 0.75;0.75 0 0.75;0.75 0.75 0;0.25 0.25 0.25];
311set(haxes,'ColorOrder',ColorOrder)
312if isfield(PlotParam,'NextPlot')
313    set(haxes,'NextPlot',PlotParam.NextPlot)
314end
315% adjust the size of the plot to include the whole field,
316if isfield(PlotParam,'FixedLimits') && isequal(PlotParam.FixedLimits,1)  %adjust the graph limits*
317    set(haxes,'XLimMode', 'manual')
318    set(haxes,'YLimMode', 'manual')
319else
320    set(haxes,'XLimMode', 'auto')
321    set(haxes,'YLimMode', 'auto')
322end
323legend_str={};
324
325%initiates string of the plot command
326plotstr='hhh=plot(';
327textmean={};
328% abscissa_name='';
329coord_x_index=[];
330test_newplot=1;
331% hh=findobj(haxes,'tag','plot_line');
332% num_curve=numel(hh);
333% icurve=0;
334for icell=1:length(CellVarIndex)
335    testfalse=0;
336    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
337    DimCell=data.VarDimName{VarIndex(1)};
338    if ischar(DimCell)
339        DimCell={DimCell};
340    end
341    XName=DimCell{1}; %first dimension considered as abscissa
342    if ~isempty(VarType{icell}.coord_x)
343        coord_x_index=VarType{icell}.coord_x;
344    else
345        coord_x_index_cell=VarType{icell}.coord(1);
346        if isequal(coord_x_index_cell,0)
347            continue  % the cell has no abscissa, skip it
348        end
349        if ~isempty(coord_x_index)&&~isequal(coord_x_index_cell,coord_x_index)
350            continue %all the selected variables must have the same first dimension
351        else
352            coord_x_index=coord_x_index_cell;
353        end
354    end
355    testplot=ones(size(data.ListVarName));%default test for plotted variables
356    testcoordvar=0;
357    charplot_0='''-''';%default
358    if isfield(data,'ObjectProjMode')&& isequal(data.ObjectProjMode,'projection')
359        charplot_0='+';
360    end
361    xtitle=''; 
362   
363    xtitle=data.ListVarName{coord_x_index};
364    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
365    if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=coord_x_index && isfield(data.VarAttribute{coord_x_index},'units')
366         xtitle=[xtitle '(' data.VarAttribute{coord_x_index}.units ')'];
367    end
368    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
369%     testcoordvar=1;
370    testplot(coord_x_index)=0;
371    if ~isempty(VarType{icell}.ancillary')
372            testplot(VarType{icell}.ancillary)=0;
373    end
374    if ~isempty(VarType{icell}.warnflag')
375            testplot(VarType{icell}.warnflag)=0;
376    end
377 
378    if isfield(data,'VarAttribute')
379        VarAttribute=data.VarAttribute;
380        for ivar=1:length(VarIndex)
381             if length(VarAttribute)>=VarIndex(ivar) && isfield(VarAttribute{VarIndex(ivar)},'long_name')
382                 plotname{VarIndex(ivar)}=VarAttribute{VarIndex(ivar)}.long_name;
383             else
384                 plotname{VarIndex(ivar)}=data.ListVarName{VarIndex(ivar)};%name for display in plot A METTRE
385             end
386        end
387    end 
388%     test_newplot=0;%default
389%     if num_curve>=icurve+numel(find(testplot(VarIndex)))%update existing curves
390%         if ~isempty(VarType{icell}.discrete')
391%             charplot_0='+';
392%             LineStyle='none';
393%         else
394%             charplot_0='none';
395%             LineStyle='-';
396%         end
397%         for ivar=1:length(VarIndex)
398%             if testplot(VarIndex(ivar))
399%                 icurve=icurve+1;
400%                 VarName=data.ListVarName{VarIndex(ivar)};
401%                 eval(['data.' VarName '=squeeze(data.' VarName ');'])
402%                 set(hh(icurve),'LineStyle',LineStyle)
403%                 set(hh(icurve),'Marker',charplot_0)
404%                 set(hh(icurve),'XData',coord_x{icell})
405%                 eval(['yy=data.' VarName ';'])
406%                 set(hh(icurve),'YData',yy);
407%             end
408%         end
409%     else% new plot
410        if ~isempty(VarType{icell}.discrete')
411            charplot_0='''+''';
412        else
413            charplot_0='''-''';
414        end
415        for ivar=1:length(VarIndex)
416            if testplot(VarIndex(ivar))
417                VarName=data.ListVarName{VarIndex(ivar)};
418                eval(['data.' VarName '=squeeze(data.' VarName ');'])
419%                 if isequal(VarName,'A')
420%                     charplot='''-''';
421%                 else
422%                     charplot=charplot_0;
423%                 end
424                plotstr=[plotstr 'coord_x{' num2str(icell) '},data.' VarName ',' charplot_0 ','];
425                eval(['nbcomponent2=size(data.' VarName ',2);']);
426                eval(['nbcomponent1=size(data.' VarName ',1);']);
427                if numel(coord_x{icell})==2
428                    coord_x{icell}=linspace(coord_x{icell}(1),coord_x{icell}(2),nbcomponent1);
429                end
430                eval(['varmean=mean(double(data.' VarName '));']);%mean value
431                textmean=[textmean; {[VarName 'mean= ' num2str(varmean,4)]}];
432                if nbcomponent1==1|| nbcomponent2==1
433                    legend_str=[legend_str {VarName}]; %variable with one component
434                else  %variable with severals  components
435                    for ic=1:min(nbcomponent1,nbcomponent2)
436                        legend_str=[legend_str [VarName '_' num2str(ic)]]; %variable with severals  components
437                    end                                                   % labeled by their index (e.g. color component)
438                end
439            end
440        end
441%     end
442end
443if test_newplot && ~isequal(plotstr,'hhh=plot(')
444    plotstr=[plotstr '''tag'',''plot_line'');'];
445                %execute plot (instruction  plotstr) 
446    eval(plotstr)
447   
448                %%%%%
449    grid(haxes, 'on')
450    hxlabel=xlabel(xtitle);
451    set(hxlabel,'Interpreter','none')% desable tex interpreter
452    if length(legend_str)>=1
453        hylabel=ylabel(legend_str{end});
454        set(hylabel,'Interpreter','none')% desable tex interpreter
455    end
456    if ~isempty(legend_str)
457        hlegend=findobj(hfig,'Tag','legend');
458        if isempty(hlegend)
459            hlegend=legend(legend_str);
460            txt=ver;
461            Release=txt(1).Release;
462            relnumb=str2num(Release(3:4));
463            if relnumb >= 14
464                set(hlegend,'Interpreter','none')% desable tex interpreter
465            end
466        else
467            legend_old=get(hlegend,'String');
468            if isequal(size(legend_old,1),size(legend_str,1))&&~isequal(legend_old,legend_str)
469                set(hlegend,'String',[legend_old legend_str]);
470            end
471        end
472    end
473    title_str='';
474    if isfield(data,'filename')
475       [Path, title_str, ext]=fileparts(data.filename);
476       title_str=[title_str ext];
477    end
478    if isfield(data,'Action')
479        if ~isequal(title_str,'')
480            title_str=[title_str ', '];
481        end
482        title_str=[title_str data.Action];
483    end
484    htitle=title(title_str);
485    txt=ver;
486    Release=txt(1).Release;
487    relnumb=str2num(Release(3:4));
488    if relnumb >= 14
489        set(htitle,'Interpreter','none')% desable tex interpreter
490    end
491    % A REPRENDRE Mean
492%         hlist=findobj(gcf,'Style','listbox','Tag','liststat');
493%         if isempty(hlist)
494%             'text'
495%             textmean
496%             set(gca,'position',[0.13,0.2,0.775,0.73])
497%             uicontrol('Style','popupmenu','Position',[20 20 200 20],'String',textmean,'Tag','liststat');
498%         else
499%             set(hlist(1),'String',textmean)
500%         end
501end
502
503
504%-------------------------------------------------------------------
505function [AxeData,haxes,PlotParamOut,PlotType]=plot_plane(Data,CellVarIndex,VarTypeCell,haxes,PlotParam,htext,PosColorbar)
506%-------------------------------------------------------------------
507grid(haxes, 'off')
508%default plotting parameters
509PlotType='plane';%default
510if ~exist('PlotParam','var')
511    PlotParam=[];
512end
513if ~isfield(PlotParam,'Scalar')
514    PlotParam.Scalar=[];
515end
516if ~isfield(PlotParam,'Vectors')
517    PlotParam.Vectors=[];
518end
519PlotParamOut=PlotParam;%default
520
521%plotting axes
522hfig=get(haxes,'parent');
523hcol=findobj(hfig,'Tag','Colorbar'); %look for colorbar axes
524hima=findobj(haxes,'Tag','ima');% search existing image in the current axes
525AxeData=get(haxes,'UserData'); %default
526if ~isstruct(AxeData)% AxeData must be a structure
527    AxeData=[];
528end
529AxeData.NbDim=2;
530if isfield(Data,'ObjectCoord')
531    AxeData.ObjectCoord=Data.ObjectCoord;
532end
533
534test_ima=0; %default: test for image or map plot
535test_vec=0; %default: test for vector plots
536test_black=0;
537test_false=0;
538test_C=0;
539XName='';
540x_units='';
541YName='';
542y_units='';
543for icell=1:length(CellVarIndex) % length(CellVarIndex) =1 or 2 (from the calling function)
544    VarType=VarTypeCell{icell};
545    ivar_X=VarType.coord_x; % defines (unique) index for the variable representing unstructured x coordinate (default =[])
546    ivar_Y=VarType.coord_y; % defines (unique)index for the variable representing unstructured y coordinate (default =[])
547    ivar_U=VarType.vector_x; % defines (unique) index for the variable representing x vector component (default =[])
548    ivar_V=VarType.vector_y; % defines (unique) index for the variable representing y vector component (default =[])
549    ivar_C=[VarType.scalar VarType.image VarType.color VarType.ancillary]; %defines index (indices) for the scalar or ancillary fields
550    if numel(ivar_C)>1
551        msgbox_uvmat('ERROR','error in plot_field: too many scalar inputs')
552        return
553    end
554    ivar_F=VarType.warnflag; %defines index (unique) for warning flag variable
555    ivar_FF=VarType.errorflag; %defines index (unique) for error flag variable
556    ind_coord=find(VarType.coord);
557    if numel(ind_coord)==2
558        VarType.coord=VarType.coord(ind_coord);
559    end
560%     idim_Y=[]; 
561    test_grid=0;
562    if ~isempty(ivar_U) && ~isempty(ivar_V)% vector components detected
563        if test_vec
564            msgbox_uvmat('ERROR','error in plot_field: attempt to plot two vector fields')
565            return
566        else
567            test_vec=1;
568            eval(['vec_U=Data.' Data.ListVarName{ivar_U} ';'])
569            eval(['vec_V=Data.' Data.ListVarName{ivar_V} ';'])
570            if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates or structured ones (then ivar_X and ivar_Y empty)     
571                eval(['vec_X=Data.' Data.ListVarName{ivar_X} ';'])
572                eval(['vec_Y=Data.' Data.ListVarName{ivar_Y} ';'])
573            elseif numel(VarType.coord)==2 & VarType.coord~=[0 0];%coordinates defines by dimension variables
574                eval(['y=Data.' Data.ListVarName{VarType.coord(1)} ';'])
575                eval(['x=Data.' Data.ListVarName{VarType.coord(2)} ';'])
576                if numel(y)==2 % y defined by first and last values on aregular mesh
577                    y=linspace(y(1),y(2),size(vec_U,1));
578                end
579                if numel(x)==2 % y defined by first and last values on aregular mesh
580                    x=linspace(x(1),x(2),size(vec_U,2));
581                end
582                [vec_X,vec_Y]=meshgrid(x,y); 
583            else
584                msgbox_uvmat('ERROR','error in plot_field: invalid coordinate definition for vector field')
585                return
586            end
587            if ~isempty(ivar_C)
588                 eval(['vec_C=Data.' Data.ListVarName{ivar_C} ';']) ;
589                 vec_C=reshape(vec_C,1,numel(vec_C));
590                 test_C=1;
591            end
592            if ~isempty(ivar_F)%~(isfield(PlotParam.Vectors,'HideWarning')&& isequal(PlotParam.Vectors.HideWarning,1))
593                if test_vec
594                    eval(['vec_F=Data.' Data.ListVarName{ivar_F} ';']) % warning flags for  dubious vectors
595                    if  ~(isfield(PlotParam.Vectors,'HideWarning') && isequal(PlotParam.Vectors.HideWarning,1))
596                        test_black=1;
597                    end
598                end
599            end
600            if ~isempty(ivar_FF) %&& ~test_false
601                if test_vec% TODO: deal with FF for structured coordinates
602                    eval(['vec_FF=Data.' Data.ListVarName{ivar_FF} ';']) % flags for false vectors
603                end
604            end
605        end
606    elseif ~isempty(ivar_C) %scalar or image
607        if test_ima
608             msgbox_uvmat('ERROR','attempt to plot two scalar fields or images')
609            return
610        end
611        eval(['A=squeeze(Data.' Data.ListVarName{ivar_C} ');']) ;% scalar represented as color image
612        test_ima=1;
613        if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates or structured ones (then ivar_X and ivar_Y empty)
614            XName=Data.ListVarName{ivar_X};
615            YName=Data.ListVarName{ivar_Y};
616            eval(['AX=Data.' XName ';'])
617            eval(['AY=Data.' YName ';'])
618            [A,AX,AY]=proj_grid(AX',AY',A',[],[],'np>256');  % interpolate on a grid 
619            if isfield(Data,'VarAttribute')
620                if numel(Data.VarAttribute)>=ivar_X && isfield(Data.VarAttribute{ivar_X},'units')
621                    x_units=['(' Data.VarAttribute{ivar_X}.units ')'];
622                end
623                if numel(Data.VarAttribute)>=ivar_Y && isfield(Data.VarAttribute{ivar_Y},'units')
624                    y_units=['(' Data.VarAttribute{ivar_Y}.units ')'];
625                end
626            end       
627        elseif numel(VarType.coord)==2 %structured coordinates
628            XName=Data.ListVarName{VarType.coord(2)};
629            YName=Data.ListVarName{VarType.coord(1)};
630            eval(['AY=Data.' Data.ListVarName{VarType.coord(1)} ';'])
631            eval(['AX=Data.' Data.ListVarName{VarType.coord(2)} ';'])
632            test_interp_X=0; %default, regularly meshed X coordinate
633            test_interp_Y=0; %default, regularly meshed Y coordinate
634            if isfield(Data,'VarAttribute')
635                if numel(Data.VarAttribute)>=VarType.coord(2) && isfield(Data.VarAttribute{VarType.coord(2)},'units')
636                    x_units=['(' Data.VarAttribute{VarType.coord(2)}.units ')'];
637                end
638                if numel(Data.VarAttribute)>=VarType.coord(1) & isfield(Data.VarAttribute{VarType.coord(1)},'units')
639                    y_units=['(' Data.VarAttribute{VarType.coord(1)}.units ')'];
640                end
641            end 
642            if numel(AY)>2
643                DAY=diff(AY);
644                DAY_min=min(DAY);
645                DAY_max=max(DAY);
646                if sign(DAY_min)~=sign(DAY_max);% =1 for increasing values, 0 otherwise
647                     errormsg=['errror in plot_field.m: non monotonic dimension variable # ' ListVarName{VarType.coord(1)} ];
648                      return
649                end
650                test_interp_Y=(DAY_max-DAY_min)> 0.0001*abs(DAY_max);
651            end
652            if numel(AX)>2
653                DAX=diff(AX);
654                DAX_min=min(DAX);
655                DAX_max=max(DAX);
656                if sign(DAX_min)~=sign(DAX_max);% =1 for increasing values, 0 otherwise
657                     errormsg=['errror in plot_field.m: non monotonic dimension variable # ' ListVarName{VarType.coord(2)} ];
658                      return
659                end
660                test_interp_X=(DAX_max-DAX_min)> 0.0001*abs(DAX_max);
661            end 
662            if test_interp_Y         
663                npxy(1)=max([256 floor((AY(end)-AY(1))/DAY_min) floor((AY(end)-AY(1))/DAY_max)]);
664                yI=linspace(AY(1),AY(end),npxy(1));
665                if ~test_interp_X
666                    xI=linspace(AX(1),AX(end),size(A,2));%default
667                    AX=xI;
668                end
669            end
670            if test_interp_X 
671                npxy(1)=max([256 floor((AX(end)-AX(1))/DAX_min) floor((AX(end)-AX(1))/DAX_max)]);
672                xI=linspace(AX(1),AX(end),npxy(2));   
673                if ~test_interp_Y
674                   yI=linspace(AY(1),AY(end),size(A,1));
675                   AY=yI;
676                end
677            end
678            if test_interp_X || test_interp_Y               
679                [AX2D,AY2D]=meshgrid(AX,AY);
680                A=interp2(AX2D,AY2D,double(A),xI,yI');
681            end
682            AX=[AX(1) AX(end)];% keep only the lower and upper bounds for image represnetation
683            AY=[AY(1) AY(end)];
684        else
685            msgbox_uvmat('ERROR','error in plot_field: invalid coordinate definition ')
686            return
687        end
688          x_label=[Data.ListVarName{ivar_X} '(' x_units ')'];
689    end       
690%     if isfield(Data,'VarAttribute')
691%         VarAttribute=Data.VarAttribute;
692%     end   
693end
694
695%%%%%%%%%%%%%%%%%%%%%   image or scalar plot %%%%%%%%%%%%%%%%%%%%%%%%%%
696
697if ~isfield(PlotParam.Scalar,'Contours')
698    PlotParam.Scalar.Contours=0; %default
699end
700PlotParamOut=PlotParam; %default
701if test_ima
702    % distinguish B/W and color images
703    np=size(A);%size of image
704    siz=numel(np);
705    if siz>3
706        msgbox_uvmat('ERROR','unrecognized scalar type ')
707            return
708    end
709    if siz==3
710        if np(3)==1
711            siz=2;%B W image
712        elseif np(3)==3
713            siz=3;%color image
714        else
715             msgbox_uvmat('ERROR',['unrecognized scalar type: ' num2str(np(3)) ' color components'])
716            return
717        end
718    end
719    %set the color map
720    if isfield(PlotParam.Scalar,'BW')
721        BW=PlotParam.Scalar.BW; %test for BW gray scale images
722    else
723        BW=(siz==2) && (isa(A,'uint8')|| isa(A,'uint16'));% non color images represented in gray scale by default
724    end
725    if siz==2 %for black and white images
726        if ~isfield(PlotParam.Scalar,'AutoScal')
727            PlotParam.Scalar.AutoScal=0;%default
728        end
729        if ~isfield(PlotParam.Scalar,'MinA')
730            PlotParam.Scalar.MinA=[];%default
731        end
732        if ~isfield(PlotParam.Scalar,'MaxA')
733            PlotParam.Scalar.MaxA=[];%default
734        end
735        if isequal(PlotParam.Scalar.AutoScal,0)|isempty(PlotParam.Scalar.MinA)|~isa(PlotParam.Scalar.MinA,'double')  %correct if there is no numerical data in edit box
736            MinA=double(min(min(A)));
737        else
738            MinA=PlotParam.Scalar.MinA; 
739        end;
740        if isequal(PlotParam.Scalar.AutoScal,0)||isempty(PlotParam.Scalar.MaxA)||~isa(PlotParam.Scalar.MaxA,'double') %correct if there is no numerical data in edit box
741            MaxA=double(max(max(A)));
742        else
743            MaxA=PlotParam.Scalar.MaxA; 
744        end;
745        PlotParamOut.Scalar.MinA=MinA;
746        PlotParamOut.Scalar.MaxA=MaxA;
747        axes(haxes)
748        if isequal(PlotParam.Scalar.Contours,1)
749            if ~isempty(hima) & ishandle(hima)
750                delete(hima)
751            end
752            if ~isfield(PlotParam.Scalar,'IncrA')
753                PlotParam.Scalar.IncrA=NaN;
754            end
755            if isnan(PlotParam.Scalar.IncrA)% | PlotParam.Scalar.AutoScal==0
756                cont=colbartick(MinA,MaxA);
757                intercont=cont(2)-cont(1);%default
758                PlotParamOut.Scalar.IncrA=intercont;
759            else
760               intercont=PlotParam.Scalar.IncrA;
761            end
762            B=A;           
763            abscontmin=intercont*floor(MinA/intercont);
764            abscontmax=intercont*ceil(MaxA/intercont);
765            contmin=intercont*floor(min(min(B))/intercont);
766            contmax=intercont*ceil(max(max(B))/intercont);
767            cont_pos_plus=0:intercont:contmax;
768            cont_pos_min=double(contmin):intercont:-intercont;
769            cont_pos=[cont_pos_min cont_pos_plus];
770            sizpx=(AX(end)-AX(1))/(np(2)-1);
771            sizpy=(AY(1)-AY(end))/(np(1)-1);
772            x_cont=AX(1):sizpx:AX(end); % pixel x coordinates for image display
773            y_cont=AY(1):-sizpy:AY(end); % pixel x coordinates for image display
774            txt=ver;%version of Matlab
775            Release=txt(1).Release;
776            relnumb=str2num(Release(3:4));
777            if relnumb >= 14
778                    vec=linspace(0,1,(abscontmax-abscontmin)/intercont);%define a greyscale colormap with steps intercont
779                map=[vec' vec' vec'];
780                colormap(map);
781                [var,hcontour]=contour(x_cont,y_cont,B,cont_pos);       
782                set(hcontour,'Fill','on')
783                set(hcontour,'LineStyle','none')
784                hold on
785            end
786            [var_p,hcontour_p]=contour(x_cont,y_cont,B,cont_pos_plus,'k-');
787            hold on
788            [var_m,hcontour_m]=contour(x_cont,y_cont,B,cont_pos_min,':');
789            set(hcontour_m,'LineColor',[1 1 1])
790            hold off
791            caxis([abscontmin abscontmax])
792            colormap(map);
793        end
794        if ~isequal(PlotParam.Scalar.Contours,1) 
795            % rescale the grey levels with min and max, put a grey scale colorbar
796            if BW
797                B=A;
798                vec=linspace(0,1,255);%define a linear greyscale colormap
799                map=[vec' vec' vec'];
800                colormap(map);  %grey scale color map
801            else
802                B=A;
803                colormap('default'); % standard faulse colors for div, vort , scalar fields
804            end
805        end
806    else %color images
807        axes(haxes)
808        if BW
809            B=uint16(sum(A,3));
810        else
811            B=uint8(A);
812        end
813        MinA=0;
814        MaxA=255;
815    end
816    if ~isequal(PlotParam.Scalar.Contours,1)
817        %interpolate to increase resolution
818        test_interp=1;
819        if max(np) <= 64
820            npxy=8*np;% increase the resolution 8 times
821        elseif max(np) <= 128
822            npxy=4*np;% increase the resolution 4 times
823        elseif max(np) <= 256
824            npxy=2*np;% increase the resolution 2 times
825        else
826            npxy=np;
827            test_interp=0; % no interpolation done
828        end
829        if test_interp==1%if we interpolate   
830            x=linspace(AX(1),AX(2),np(2));
831            y=linspace(AY(1),AY(2),np(1));
832            [X,Y]=meshgrid(x,y);
833            xi=linspace(AX(1),AX(2),npxy(2));
834            yi=linspace(AY(1),AY(2),npxy(1));
835            B = interp2(X,Y,double(B),xi,yi');
836        end       
837        if isempty(hima)
838            tag=get(haxes,'Tag');
839            hima=imagesc(AX,AY,B,[MinA MaxA]);
840            set(hima,'Tag','ima','HitTest','off')
841            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)       
842        else
843            set(hima,'CData',B);
844            if MinA<MaxA
845                caxis([MinA MaxA])
846            else
847                caxis([MinA MinA+1])
848            end
849            set(hima,'XData',AX);
850            set(hima,'YData',AY);
851        end
852    end
853    if ~isstruct(AxeData)
854        AxeData=[];
855    end
856    AxeData.A=A;
857    AxeData.AX=[AX(1) AX(end)];
858    AxeData.AY=[AY(1) AY(end)];
859    test_ima=1;
860    %display the colorbar code for B/W images if Poscolorbar not empty
861    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
862        if isempty(hcol)||~ishandle(hcol)
863             hcol=colorbar;%create new colorbar
864        end
865        if length(PosColorbar)==4
866                 set(hcol,'Position',PosColorbar)           
867        end
868        YTick=0;%default
869        if MaxA>MinA
870            if isequal(PlotParam.Scalar.Contours,1)
871                colbarlim=get(hcol,'YLim');
872                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);               
873                YTick=cont_pos(2:end-1);
874                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
875                set(hcol,'YTick',YTick_scaled);
876            elseif (isfield(PlotParam.Scalar,'BW') & isequal(PlotParam.Scalar.BW,1))|isa(A,'uint8')| isa(A,'uint16')%images
877                hi=get(hcol,'children');
878                if iscell(hi)%multiple images in colorbar
879                    hi=hi{1};
880                end
881                set(hi,'YData',[MinA MaxA])
882                set(hi,'CData',[1:256]')
883                set(hcol,'YLim',[MinA MaxA])
884                YTick=colbartick(MinA,MaxA);
885                set(hcol,'YTick',YTick)               
886            else
887                hi=get(hcol,'children');
888                if iscell(hi)%multiple images in colorbar
889                    hi=hi{1};
890                end
891                set(hi,'YData',[MinA MaxA])
892                set(hi,'CData',[1:64]')
893                YTick=colbartick(MinA,MaxA);
894                set(hcol,'YLim',[MinA MaxA])
895                set(hcol,'YTick',YTick)
896            end
897            set(hcol,'Yticklabel',num2str(YTick'));
898        end
899    elseif ishandle(hcol)
900        delete(hcol); %erase existing colorbar if not needed
901    end
902else%no scalar plot
903    if ~isempty(hima) && ishandle(hima)
904        delete(hima)
905    end
906    if ~isempty(hcol)&& ishandle(hcol)
907       delete(hcol)
908    end
909    AxeData.A=[];
910    AxeData.AX=[];
911    AxeData.AY=[];
912    PlotParamOut=rmfield(PlotParamOut,'Scalar');
913end
914
915%%%%%%%%%%%%%%%%%%%%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
916if test_vec
917   %vector scale representation
918    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
919        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
920    end   
921    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
922    vec_Y=reshape(vec_Y,1,numel(vec_Y));
923    vec_U=reshape(vec_U,1,numel(vec_U));
924    vec_V=reshape(vec_V,1,numel(vec_V));
925    MinMaxX=max(vec_X)-min(vec_X);
926    MinMaxY=max(vec_Y)-min(vec_Y);
927    AxeData.Mesh=sqrt((MinMaxX*MinMaxY)/length(vec_X));
928    if  ~isfield(PlotParam.Vectors,'AutoVec') || isequal(PlotParam.Vectors.AutoVec,0)|| ~isfield(PlotParam.Vectors,'VecScale')...
929               ||isempty(PlotParam.Vectors.VecScale)||~isa(PlotParam.Vectors.VecScale,'double') %automatic vector scale
930        scale=[];
931        if test_false %remove false vectors
932            indsel=find(AxeData.FF==0);%indsel =indices of good vectors
933        else     
934            indsel=[1:numel(vec_X)];%
935        end
936        if isempty(vec_U)
937            scale=1;
938        else
939            if isempty(indsel)
940                MaxU=max(abs(vec_U));
941                MaxV=max(abs(vec_V));
942            else
943                MaxU=max(abs(vec_U(indsel)));
944                MaxV=max(abs(vec_V(indsel)));
945            end
946            scale=MinMaxX/(max(MaxU,MaxV)*50);
947            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
948        end
949    else
950        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
951    end;
952   
953    %record vectors on the plotting axes
954    if test_C==0
955        vec_C=ones(1,numel(vec_X));
956    end
957    AxeData.X=vec_X';
958    AxeData.Y=vec_Y';
959    AxeData.U=vec_U';
960    AxeData.V=vec_V';
961    AxeData.C=vec_C';
962    if isempty(ivar_F)
963        AxeData.F=[];
964    else
965        AxeData.F=vec_F';
966    end
967    if isempty(ivar_FF)
968        AxeData.FF=[];
969    else
970        AxeData.FF=vec_FF';
971    end
972   
973    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
974    if isfield(PlotParam.Vectors,'decimate4')&isequal(PlotParam.Vectors.decimate4,1)
975        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
976        dy_thresh=max(abs(diffy))/2;
977        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
978        ind_sel=1:ind_jump(1);%select the first line
979        for i=2:2:length(ind_jump)-1
980            ind_sel=[ind_sel [ind_jump(i)+1:ind_jump(i+1)]];% select the odd lines
981        end
982        nb_sel=length(ind_sel);
983        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
984        vec_X=vec_X(ind_sel);
985        vec_Y=vec_Y(ind_sel);
986        vec_U=vec_U(ind_sel);
987        vec_V=vec_V(ind_sel);
988        vec_C=vec_C(ind_sel);
989        if ~isempty(ivar_F)
990           vec_F=vec_F(ind_sel);
991        end
992        if ~isempty(ivar_FF)
993           vec_FF=vec_FF(ind_sel);
994        end
995    end
996   
997    %get main level color code
998    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
999   
1000    % take flags into account: add flag colors to the list of colors
1001    sizlist=size(colorlist);
1002    nbcolor=sizlist(1);
1003    if test_black
1004       nbcolor=nbcolor+1;
1005       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
1006       if ~isempty(ivar_FF)
1007            ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
1008       else
1009            ind_flag=find(vec_F~=1 & vec_F~=0);
1010       end
1011       col_vec(ind_flag)=nbcolor;   
1012    end
1013    nbcolor=nbcolor+1;
1014    if ~isempty(ivar_FF)
1015        ind_flag=find(vec_FF~=0);
1016        if isfield(PlotParam.Vectors,'HideFalse') && PlotParam.Vectors.HideFalse==1
1017            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
1018        else
1019            colorlist(nbcolor,:)=[1 0 1];% magenta color
1020        end
1021        col_vec(ind_flag)=nbcolor;
1022    end
1023    %plot vectors:
1024    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
1025
1026else
1027    hvec=findobj(haxes,'Tag','vel');
1028    if ~isempty(hvec)
1029        delete(hvec);
1030    end
1031    AxeData.X=[];
1032    AxeData.Y=[];
1033    AxeData.U=[];
1034    AxeData.V=[];
1035    AxeData.C=[];
1036    AxeData.W=[];
1037    AxeData.F=[];
1038     AxeData.FF=[];
1039    AxeData.Mesh=[];
1040    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1041end
1042if isfield(Data,'Z')
1043    AxeData.Z=Data.Z;% A REVOIR
1044end
1045listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1046listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1047Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1048ind_select=[];
1049nbvar=0;
1050AxeData.ListVarName={};
1051AxeData.VarDimName={};
1052AxeData.VarAttribute={};
1053for ilist=1:numel(listfields)
1054    eval(['testvar=isfield(AxeData,listfields{ilist}) && ~isempty(AxeData.' listfields{ilist} ');'])
1055    if testvar
1056        nbvar=nbvar+1;
1057        AxeData.ListVarName{nbvar}=listfields{ilist};
1058        AxeData.VarDimName{nbvar}=listdim{ilist};
1059        AxeData.VarAttribute{nbvar}.Role=Role{ilist};
1060    end
1061end
1062%store the coordinate extrema occupied by the field
1063test_lim=0;
1064if test_vec
1065    Xlim=[min(vec_X) max(vec_X)];
1066    Ylim=[min(vec_Y) max(vec_Y)];
1067    test_lim=1;
1068    if test_ima%both background image and vectors coexist, take the wider bound
1069        Xlim(1)=min(AX(1),Xlim(1));
1070        Xlim(2)=max(AX(end),Xlim(2));
1071        Ylim(1)=min(AY(end),Ylim(1));
1072        Ylim(2)=max(AY(1),Ylim(2));
1073    end
1074elseif test_ima %only image plot
1075    Xlim(1)=min(AX(1),AX(end));
1076    Xlim(2)=max(AX(1),AX(end));
1077    Ylim(1)=min(AY(1),AY(end));
1078    Ylim(2)=max(AY(1),AY(end));
1079    test_lim=1;
1080end
1081AxeData.RangeX=Xlim;
1082AxeData.RangeY=Ylim;
1083% adjust the size of the plot to include the whole field, except if PlotParam.FixedLimits=1
1084if ~(isfield(PlotParam,'FixedLimits') && PlotParam.FixedLimits) && test_lim
1085        if Xlim(2)>Xlim(1)
1086            set(haxes,'XLim',Xlim);% set x limits of frame in axes coordinates
1087        end
1088        if Ylim(2)>Ylim(1)
1089            set(haxes,'YLim',Ylim);% set y limits of frame in axes coordinate
1090        end
1091end
1092if ~(isfield(PlotParam,'Auto_xy') && isequal(PlotParam.Auto_xy,1))
1093     set(haxes,'DataAspectRatio',[1 1 1])
1094end
1095set(haxes,'YDir','normal')
1096set(get(haxes,'XLabel'),'String',[XName x_units]);
1097set(get(haxes,'YLabel'),'String',[YName y_units]);
1098
1099%-------------------------------------------------------------------
1100% --- function for plotting vectors
1101%INPUT:
1102% haxes: handles of the plotting axes
1103% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1104% scale: scaling factor for vector length representation
1105% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1106% col_vec: matlab vector setting the color number #i for each velocity vector
1107function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1108%-------------------------------------------------------------------
1109%define arrows
1110theta=0.5 ;%angle arrow
1111alpha=0.3 ;%length arrow
1112rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1113%find the existing lines
1114%h=findobj(gca,'Type','Line');% search existing lines in the current axes
1115h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1116sizh=size(h);
1117set(h,'EraseMode','xor');
1118set(haxes,'NextPlot','replacechildren');
1119     
1120%drawnow
1121%create lines (if no lines) or modify them
1122if ~isequal(size(col_vec),size(x))
1123    col_vec=ones(size(x));% case of error in col_vec input
1124end
1125sizlist=size(colorlist);
1126ncolor=sizlist(1);
1127
1128for icolor=1:ncolor
1129    %determine the line positions for each color icolor
1130    ind=find(col_vec==icolor);
1131    xc=x(ind);
1132    yc=y(ind);
1133    uc=u(ind)*scale;
1134    vc=v(ind)*scale;
1135    n=size(xc);
1136    xN=NaN*ones(size(xc));
1137    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1138%     matx=[xc(:) xc(:)+uc(:) xN(:)]';
1139    matx=reshape(matx,1,3*n(2));
1140    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1141%     maty=[yc(:) yc(:)+vc(:) xN(:)]';
1142    maty=reshape(maty,1,3*n(2));
1143   
1144    %determine arrow heads
1145    arrowplus=rot*[uc;vc];
1146    arrowmoins=rot'*[uc;vc];
1147    x1=xc+uc/2-arrowplus(1,:);
1148    x2=xc+uc/2;
1149    x3=xc+uc/2-arrowmoins(1,:);
1150    y1=yc+vc/2-arrowplus(2,:);
1151    y2=yc+vc/2;
1152    y3=yc+vc/2-arrowmoins(2,:);
1153%     x1=xc+uc-arrowplus(1,:);
1154%     x2=xc+uc;
1155%     x3=xc+uc-arrowmoins(1,:);
1156%     y1=yc+vc-arrowplus(2,:);
1157%     y2=yc+vc;
1158%     y3=yc+vc-arrowmoins(2,:);
1159    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1160    matxar=reshape(matxar,1,4*n(2));
1161    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1162    matyar=reshape(matyar,1,4*n(2));
1163    %draw the line or modify the existing ones
1164      hx = [x1;x2;x3];
1165      hy = [y1;y2;y3];
1166    tri=reshape([1:3*length(uc)],3,[])';
1167    d = tri(:,[1 2 3 1])';
1168   
1169    isn=isnan(colorlist(icolor,:));%test if color NaN
1170    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1171        axes(haxes)
1172        if ~isn(1) %if the vectors are visible color not nan
1173            if n(2)>0
1174                hold on
1175                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1176                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1177%                 fill(hx(d),hy(d),colorlist(icolor,:),'EdgeColor','none','
1178%                 Tag','Vel');
1179          end
1180        end
1181    else
1182        if isn(1)
1183            delete(h(2*icolor-1))
1184            delete(h(2*icolor))
1185        else
1186            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1187            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1188            set(h(2*icolor-1),'EraseMode','xor');
1189            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1190            set(h(2*icolor),'Color',colorlist(icolor,:));
1191            set(h(2*icolor),'EraseMode','xor');
1192        end
1193     end
1194end
1195if sizh(1) > 2*ncolor
1196    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1197        delete(h(2*icolor-1))
1198        delete(h(2*icolor))
1199    end
1200end
1201
1202%-------------------------------------------------------------------
1203% ---- determine tick positions for colorbar
1204function YTick=colbartick(MinA,MaxA)
1205%-------------------------------------------------------------------
1206%determine tick positions with "simple" values between MinA and MaxA
1207YTick=0;%default
1208maxabs=max([abs(MinA) abs(MaxA)]);
1209if maxabs>0
1210ord=10^(floor(log10(maxabs)));%order of magnitude
1211div=1;
1212siz2=1;
1213while siz2<2
1214%     values=[-9:div:9];
1215    values=-10:div:10;
1216    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1217    siz=size(ind);
1218    if siz(2)<4%if there are less than 4 selected values (4 levels)
1219        values=-9:0.5*div:9;
1220        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1221    end
1222    siz2=size(ind,2);
1223%     siz2=siz(2)
1224    div=div/10;
1225end
1226YTick=ord*values(ind);
1227end
1228
Note: See TracBrowser for help on using the repository browser.