source: trunk/src/plot_field.m @ 206

Last change on this file since 206 was 206, checked in by sommeria, 10 years ago

bug fixes to deal with volumes, storage of ACTION menu in series fixed

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