Sunday, June 26, 2011

[Matlab] create a faked colorbar in matlab

function newhcb=plotcolorbar(hcbar,cmap)
% create a colorbar using true color (fill function) to replace the existing one created by matlab itself
% Usage: newHandle=plotcolorbar(h,cmap)
% copyright @ http://scriptdemo.blogspot.com

if nargin==0
   hcbar=findobj('tag','Colorbar');
   if isempty(hcbar)
      disp('No colorbar obj found!!!'); return;
   end
   cmap=colormap;
elseif nargin==1
   if ishandle(hcbar)
      cmap=colormap;
   else
      cmap=hcbar;
      hcbar=findobj('tag','Colorbar');
      if isempty(hcbar)
         disp('No colorbar obj found!!!'); return;
      end
   end
end
oriNPlot=get(gcf,'NextPlot');
set(gcf,'NextPlot','add');
oriH=gca;
oriPos=get(oriH,'position');

cbarpos=get(hcbar,'position');
cbarxlim=get(hcbar,'xlim'); cbarxtick=get(hcbar,'xtick'); cbarxticklabel=get(hcbar,'xticklabel');
cbarylim=get(hcbar,'ylim'); cbarytick=get(hcbar,'ytick'); cbaryticklabel=get(hcbar,'yticklabel');
newHcbar=axes('Position',cbarpos,'tag','newColorbar');
NC=size(cmap,1);
if isempty(cbarxtick)
   %vertical
   yy=linspace(cbarylim(1),cbarylim(2),NC+1);
   yy=[yy(1:NC); yy(1:NC); yy(2:NC+1); yy(2:NC+1); yy(1:NC)];
   xx=[cbarxlim(1) cbarxlim(2) cbarxlim(2) cbarxlim(1) cbarxlim(1)];
   xx=xx'*ones(1,NC);
else
   %horizontal
   xx=linspace(cbarxlim(1),cbarxlim(2),NC+1);
   xx=[xx(1:NC); xx(1:NC); xx(2:NC+1); xx(2:NC+1); xx(1:NC)];
   yy=[cbarylim(1) cbarylim(2) cbarylim(2) cbarylim(1) cbarylim(1)];
   yy=yy'*ones(1,NC);
end
for jj=1:NC
    hf=fill(xx(:,jj),yy(:,jj),cmap(jj,:)); set(hf,'linestyle','none'); hold on;
end
set(newHcbar,'YAxisLocation',get(hcbar,'YAxisLocation'), ...
             'XAxisLocation',get(hcbar,'XAxisLocation'), ...
             'YScale',get(hcbar,'YScale'), 'XScale',get(hcbar,'XScale'), ...
             'TickDir',get(hcbar,'TickDir'), ...
             'xlim',cbarxlim,'ylim',cbarylim, ...
             'xtick',cbarxtick,'ytick',cbarytick, ...
             'xticklabel',cbarxticklabel,'yticklabel',cbaryticklabel,...
             'fontweight',get(hcbar,'fontweight'), 'fontsize',get(hcbar,'fontsize'),'linewidth',get(hcbar,'linewidth'), ...
             'XDir',get(hcbar,'XDir'),'YDir',get(hcbar,'YDir'), 'XColor',get(hcbar,'XColor'),'YColor',get(hcbar,'YColor'));
set(gcf,'NextPlot',oriNPlot);
set(gcf,'CurrentAxes',oriH); colorbar off;
set(oriH,'position',oriPos)
if nargout>0, newhcb = newHcbar; end

ShowCalendar