# Barplot colors

## Matlab - Bar plot with different colors

barh(bar-IDs, bar-values, 'FaceColor', bar-color );

Simple example

barh( 1, 65 , 'FaceColor', 'blue' ); hold on

barh( [2,3,4], [50,3,5], 'FaceColor', 'red' );

barh( [5,6] , [70,8] , 'FaceColor', 'green' ); hold off

set(gca,'YTick',[1:6])

% alternatively: plot colors one by one, but set non-group values zero

Complete example

% generate percentage data, define groups, and colors

perc = [ 8; 70; 5; 3; 50; 65];

groups = [ 1; 1; 2; 2; 2; 3];

names = {'A1';'A2';'B1';'B2';'B3';'C'};

colorset = [0.3, 0.5, 0.7;... % blue

0.8, 0.3, 0.3;... % red

0.6, 0.7, 0.3] % green

% for horizontal barplot: switch order of bars

perc = flipud(perc);

groups = flipud(groups);

names = flipud(names);

colorset = flipud(colorset);

% (1) plot empty bar boxes (100 percent white box)

num = numel(perc);

box100perc = repmat(100,num,1);

barh(1:num,box100perc, 'FaceColor',[1,1,1] );

hold on;

% (2) plot colored bars separately for each color-group (set non-group values to zero):

g = unique(groups);

for i=1:numel(g)

IDs = find(ismember(groups,g(i)));

x = zeros(size(perc)); x(IDs)=perc(IDs);

barh(1:num, x, 'FaceColor',colorset(i,:) );

end

hold off

axis([0,100,0,num+1]);

xlabel('Percent')

set(gca,'YTickLabel',names)

set(gca, 'box', 'off')

title('Colored barplot', 'Color',[0.5,0,0.5])