source: trunk/src/plot_field.m @ 201

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

bug corrections. Introduction of water wheight in calibration

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