您的位置:首页 > 编程语言 > MATLAB

matlab之如何设置colormap, 以一个figure中画多幅图

2014-03-11 16:45 671 查看
原文地址:给大家一个非常好用的matlab程序(一个figure中画多幅图,colormap如何设置)作者:CrazyMatrix

function freezeColors(varargin)

% freezeColors  Lock colors of plot, enablingmultiple colormaps per figure. (v2.3)

%

%   Problem: There is only onecolormap per figure. This function provides

%      an easy solution when plots using different colomaps aredesired

%      in the same figure.

%

%   freezeColors freezes thecolors of graphics objects in the current axis so

%      that subsequent changes to the colormap (or caxis) will not changethe

%      colors of these objects. freezeColors works on any graphicsobject

%      with CData in indexed-color mode: surfaces, images,scattergroups,

%      bargroups, patches, etc. It works by converting CData to true-colorrgb

%      based on the colormap active at the time freezeColors iscalled.

%

%   The original indexed colordata is saved, and can be restored using

%      unfreezeColors, making the plot once again subject to the colormapand

%      caxis.

%

%

%   Usage:

%      freezeColors       applies to all objects in current axis (gca),

%      freezeColors(axh)   same, butworks on axis axh.

%

%   Example:

%      subplot(2,1,1); imagesc(X); colormap hot; freezeColors

%      subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...

%

%      Note: colorbars must also be frozen. Due to Matlab 'improvements'this can

%    nolonger be done with freezeColors. Instead, please

%    usethe function CBFREEZE by Carlos Adrian Vargas Aguilera

%    thatcan be downloaded from the MATLAB File Exchange

%    (http://www.mathworks.com/matlabcentral/fileexchange/24371)

%

%      h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)

%

%      For additional examples, see test/test_main.m

%

%   Side effect on render mode:freezeColors does not work with the painters

%      renderer, because Matlab doesn't support rgb color data in

%      painters mode. If the current renderer is painters,freezeColors

%      changes it to zbuffer. This may have unexpected effects on otheraspects

%      of your plots.

%

%      See also unfreezeColors, freezeColors_pub.html, cbfreeze.

%

%

%   John Iversen (iversen@nsi.edu) 3/23/05

%

%   Changes:

%   JRI (iversen@nsi.edu)4/19/06   Correctly handlesscaled integer cdata

%   JRI9/1/06   should now handle allobjects with cdata: images, surfaces,

%               scatterplots. (v 2.1)

%   JRI 11/11/06 Preserves NaNcolors. Hidden option (v 2.2, not uploaded)

%   JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v2.3)

%   JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.

%   JRI4/9/08   Fix preserving caxis forobjects within hggroups (e.g. contourf)

%   JRI4/7/10   Change documentation forcolorbars

% Hidden option for NaN colors:

%   Missing data are oftenrepresented by NaN in the indexed color

%   data, which renderstransparently. This transparency will be preserved

%   when freezing colors. Ifinstead you wish such gaps to be filled with

%   a real color, add'nancolor',[r g b] to the end of the arguments. E.g.

%   freezeColors('nancolor',[r gb]) or freezeColors(axh,'nancolor',[r g b]),

%   where [r g b] is a colorvector. This works on images & pcolor, but noton

%   surfaces.

%   Thanks to Fabiano Busdraghiand Jody Klymak for the suggestions. Bugfixes

%   attributed in the code.

% Free for all uses, but please retain the following:

%   Original Author:

%   John Iversen, 2005-10

%  john_iversen@post.harvard.edu

appdatacode = 'JRI__freezeColorsData';

[h, nancolor] = checkArgs(varargin);

%gather all children with scaled or indexed CData

cdatah = getCDataHandles(h);

%current colormap

cmap = colormap;

nColors = size(cmap,1);

cax = caxis;

% convert object color indexes into colormap to true-color datausing

%  current colormap

for hh = cdatah',

    g =get(hh);

   

    %preserveparent axis clim

    parentAx =getParentAxes(hh);

    originalClim= get(parentAx,'clim');   

  

   %   Note: Special handling ofpatches: For some reason, setting

   %   cdata on patches created bybar() yields an error,

   %   so instead we'll setfacevertexcdata instead for patches.

    if~strcmp(g.Type,'patch'),

       cdata = g.CData;

    else

       cdata = g.FaceVertexCData;

    end

   

    %get cdatamapping (most objects (except scattergroup) have it)

    ifisfield(g,'CDataMapping'),

       scalemode = g.CDataMapping;

    else

       scalemode = 'scaled';

    end

   

    %saveoriginal indexed data for use with unfreezeColors

    siz =size(cdata);

   setappdata(hh, appdatacode, {cdata scalemode});

    %convertcdata to indexes into colormap

    ifstrcmp(scalemode,'scaled'),

       %4/19/06 JRI, Accommodate scaled display of integer cdata:

       %      in MATLAB, uint * double = uint, so must coerce cdata todouble

       %      Thanks to O Yamashita for pointing this need out

       idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) *nColors);

    else %directmapping

       idx = cdata;

       /8/09 in case direct data is non-int (e.g.image;freezeColors)

       % (Floor mimics how matlab converts data into colormapindex.)

       % Thanks to D Armyr for the catch

       idx = floor(idx);

    end

   

    %clamp to[1, nColors]

   idx(idx<1) = 1;

   idx(idx>nColors) = nColors;

    %handlenans in idx

    nanmask =isnan(idx);

   idx(nanmask)=1; %temporarily replace w/ a valid colormap index

    %maketrue-color data--using current colormap

    realcolor =zeros(siz);

    for i =1:3,

       c = cmap(idx,i);

       c = reshape(c,siz);

       c(nanmask) = nancolor(i); %restore Nan (or nancolor ifspecified)

       realcolor(:,:,i) = c;

    end

   

    %apply newtrue-color color data

   

    %true-coloris not supported in painters renderer, so switch out of that

    ifstrcmp(get(gcf,'renderer'), 'painters'),

       set(gcf,'renderer','zbuffer');

    end

   

    %replaceoriginal CData with true-color data

    if~strcmp(g.Type,'patch'),

       set(hh,'CData',realcolor);

    else

       set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))

    end

   

    %restoreclim (so colorbar will show correct limits)

    if~isempty(parentAx),

       set(parentAx,'clim',originalClim)

    end

   

end %loop on indexed-color objects

%============================================================================%

% Local functions

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% getCDataHandles -- get handles of all descendents with indexedCData

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function hout = getCDataHandles(h)

% getCDataHandles  Find all objects with indexedCData

%recursively descend object tree, finding objects with indexedCData

% An exception: don't include children of objects that themselveshave CData:

%   for example, scattergroupsare non-standard hggroups, with CData. Changing

%   such a group's CDataautomatically changes the CData of its children,

%   (as well as the children'shandles), so there's no need to act on them.

error(nargchk(1,1,nargin,'struct'))

hout = [];

if isempty(h),return;end

ch = get(h,'children');

for hh = ch'

    g =get(hh);

    ifisfield(g,'CData'),    %does object have CData?

       %is it indexed/scaled?

       if ~isempty(g.CData) &&isnumeric(g.CData) &&size(g.CData,3)==1,

           hout = [hout; hh]; %#ok<AGROW> %yes,add to list

       end

    else %noCData, see if object has any interesting children

           hout = [hout; getCDataHandles(hh)];%#ok<AGROW>

    end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% getParentAxes -- return handle of axes object to which a givenobject belongs

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function hAx = getParentAxes(h)

% getParentAxes  Return enclosing axes of a givenobject (could be self)

error(nargchk(1,1,nargin,'struct'))

%object itself may be an axis

if strcmp(get(h,'type'),'axes'),

    hAx =h;

    return

end

parent = get(h,'parent');

if (strcmp(get(parent,'type'), 'axes')),

    hAx =parent;

else

    hAx =getParentAxes(parent);

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% checkArgs -- Validate input arguments

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [h, nancolor] = checkArgs(args)

% checkArgs  Validate input arguments tofreezeColors

nargs = length(args);

error(nargchk(0,3,nargs,'struct'))

%grab handle from first argument if we have an odd number ofarguments

if mod(nargs,2),

    h =args{1};

    if~ishandle(h),

       error('JRI:freezeColors:checkArgs:invalidHandle',...

           'The first argument must be a valid graphics handle (to anaxis)')

    end

    % 4/2010check if object to be frozen is a colorbar

    ifstrcmp(get(h,'Tag'),'Colorbar'),

     if ~exist('cbfreeze.m'),

       warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...

           ['You seem to be attempting to freeze a colorbar. This nolonger'...

           'works. Please read the help for freezeColors for thesolution.'])

     else

       cbfreeze(h);

       return

     end

    end

    args{1} =[];

    nargs =nargs-1;

else

    h =gca;

end

%set nancolor if that option was specified

nancolor = [nan nan nan];

if nargs == 2,

    ifstrcmpi(args{end-1},'nancolor'),

       nancolor = args{end};

       if ~all(size(nancolor)==[1 3]),

           error('JRI:freezeColors:checkArgs:badColorArgument',...

               'nancolor must be [r g b] vector');

       end

       nancolor(nancolor>1) = 1;nancolor(nancolor<0) = 0;

    else

       error('JRI:freezeColors:checkArgs:unrecognizedOption',...

           'Unrecognized option (%s). Only ''nancolor'' isvalid.',args{end-1})

    end

end

 

 

function CBH = cbfreeze(varargin)

�FREEZE   Freezes the colormap ofa colorbar.

%

%   SYNTAX:

%          cbfreeze

%          cbfreeze('off')

%          cbfreeze(H,...)

%    CBH = cbfreeze(...);

%

%   INPUT:

%    H    - Handles of colorbars to be freezed, or from figures tosearch

%            for them or from peer axes (see COLORBAR).

%            DEFAULT: gcf (freezes all colorbars from the current figure)

%    'off' - Unfreezes the colorbars, other options are:

%              'on'   Freezes

%              'un'    same as'off'

%              'del'   Deletes thecolormap(s).

%            DEFAULT: 'on' (of course)

%

%   OUTPUT (all optional):

%    CBH - Color bar handle(s).

%

%   DESCRIPTION:

%    MATLAB works with a unique COLORMAP by figure which is a big

%    limitation. Function FREEZECOLORS by John Iversen allows touse

%    different COLORMAPs in a single figure, but it fails freezingthe

%    COLORBAR. This program handles this problem.

%

%   NOTE:

%    * Optional inputs use its DEFAULT value when not given or [].

%    * Optional outputs may or not be called.

%    * If no colorbar is found, one is created.

%    * The new frozen colorbar is an axes object and does notbehaves

%      as normally colorbars when resizing the peer axes. Although,some

%      time the normal behavior is not that good.

%    * Besides, it does not have the 'Location' property anymore.

%    * But, it does acts normally: no ZOOM, no PAN, no ROTATE3D andno

%      mouse selectable.

%    * No need to say that CAXIS and COLORMAP must be defined beforeusing

%      this function. Besides, the colorbar location. Anyway, 'off'or

%      'del' may help.

%    * The 'del' functionality may be used whether or not thecolorbar(s)

%      is(are) froozen. The peer axes are resized back. Try:

%       >> colorbar, cbfreeze del

%

%   EXAMPLE:

%    surf(peaks(30))

%    colormap jet

%  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: