function [varargout] = setColor_barByGroup(varargin)
%
% SETCOLOR_BARBYGROUP change the color of a bar to same groups have the
% same color.
%
% SETCOLOR_BARBYGROUP(COLOR) change the color of a bar with N groups
% where the i-th group has the COLOR(i, :) color.
% COLOR is a N-by-3 matrix color in RGB.
%
% COLOR can be a N-by-1 cell with string matlab colors: 'r','b','g',c', etc.
% In this case function rgb.m is needed:
% http://www.mathworks.com/matlabcentral/fileexchange/1805-rgb-m
%
%
% P = SETCOLOR_BARBYGROUP(...) return in the N-by-1 vector P the new patches
% associated to each group.
%
%
% SETCOLOR_BARBYGROUP(AX, ...) AX is the axes to apply the color change.
%
%
% EXAMPLE: Change the current bar to red [1 0 0], blue [0 0 1] and green [0 1 0]
%
% bar(rand(3,5));
% color = [1 0 0; 0 0 1; 0 1 0];
% setColor_barByGroup(color);
%
%
% EXAMPLE: Change the subplot bar to the color {'r', 'b', 'g'} (needed
% funciton: rgb.m)
%
% data = rand(3,5);
% subplot(1,2,1);
% bar(data);
% subplot(1,2,2);
% bar(data);
% p = setColor_barByGroup({'r', 'b', 'g'});
%
%
% tags: figure, bar, color, groups
%
%
% author: Mar Callau-Zori
% PhD student - Universidad Politecnica de Madrid
%
% version: 1.0, December 2011.
%
[ax, color] = extractInputParameters(varargin{:});
% apply: rgb.m
if iscell(color)
if exist('rgb.m','file')
color = cell2mat(cellfun(@(x) rgb(x), color, 'UniformOutput', false)');
else
error('stat:setColor_barByGroup:notFoundRGB', 'Function rgb.m is needed');
end
end
% get the axes patches
h = findobj(ax,'type','patch');
h = h(end:-1:1);
set(h, 'Visible', 'on')
numGroups = size(get(h(1), 'Xdata'), 2);
xData_cell = get(h, 'xData');
yData_cell = get(h, 'yData');
% plot patches
p = NaN .* ones(1, numGroups);
for iGroup=1:numGroups
xData_iGroup = cell2mat(cellfun(@(x) x(:,iGroup),xData_cell ,'UniformOutput', false)');
yData_iGroup = cell2mat(cellfun(@(x) x(:,iGroup),yData_cell,'UniformOutput', false)');
p(iGroup) = patch(xData_iGroup, yData_iGroup, color(iGroup, :));
end
if nargout>0
varargout{1} = p;
end
end
function [ax, color] = extractInputParameters(varargin)
if size(varargin{1},1) == 1 && size(varargin{1},1) == 2 && ...
ishandle(varargin{1}) && strcmpi(get(varargin{1}, 'type'), 'axes')
ax = varargin{1};
varargin = varargin(2:end);
else
ax = gca;
end
if iscell(varargin{1}) || (isnumeric(varargin{1}) && length(varargin{1})==3)
color = varargin{1};
varargin = varargin(2:end);
else
error('stat:extractInputParameter:Required', 'The color_bar input parameter is required');
end
end