source: trunk/src/plot_field.m @ 192

Last change on this file since 192 was 192, checked in by sommeria, 13 years ago

civ: version working for all systems: windows, linux, mac
plots: introduction of axes limits , bug repairs (still further work needed)

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