MATLAB: Changing color of individual parts of stacked bars

barcolorstacked

I'm wondering if it is possible to change the color of the individual parts of stacked bars. My stacked bars have different amount of parts (through NaNs) and individual values have also a classification. I want to change the colors according to my classification g/gc/c.
data =[
8.5000 2.5000 25.0000 NaN NaN NaN NaN
3.0000 28.0000 32.0000 2.0000 NaN NaN NaN
23.0000 NaN NaN NaN NaN NaN NaN
3.0000 2.5000 4.5000 5.0000 9.5000 3.0000 2.5000
6.0000 21.0000 7.0000 NaN NaN NaN NaN
7.5000 34.5000 NaN NaN NaN NaN NaN
3.0000 6.0000 24.0000 NaN NaN NaN NaN
2.0000 22.0000 NaN NaN NaN NaN NaN
5.0000 37.0000 NaN NaN NaN NaN NaN
1.5000 5.5000 25.0000 NaN NaN NaN NaN
1.0000 1.0000 1.5000 23.5000 NaN NaN NaN];
class={
'g' 'gc' 'c' '' '' '' ''
'g' 'gc' 'c' 'gc' '' '' ''
'c' '' '' '' '' '' ''
'g' 'c' 'g' 'gc' 'c' 'g' 'c'
'g' 'gc' 'c' '' '' '' ''
'g' 'c' '' '' '' '' ''
'g' 'gc' 'c' '' '' '' ''
'g' 'c' '' '' '' '' ''
'g' 'c' '' '' '' '' ''
'gc' 'g' 'c' '' '' '' ''
'g' 'gc' 'g' 'c' '' '' '' };
figure
b1=bar(data,'stacked');
I know that the color of first/second/third/etc parts of all the bars can be changed, but the individuality is the problem here for me. I also tried to make the plot by one stacked bar at a time, but apparently plotting even one stacked bar is surprisingly difficult:
figure
b2=bar(data(1,:),'stacked');
somehow produces a grouped bar plot.

Best Answer

Tricking the bar plot by feeding it extra NaN data seems to work. The loop is ugly, but I can't see a nice way around it. It's a hack anyway.
You shouldn't overwrite class with a variable, as it is a useful function.
data =[
8.5000 2.5000 25.0000 NaN NaN NaN NaN
3.0000 28.0000 32.0000 2.0000 NaN NaN NaN
23.0000 NaN NaN NaN NaN NaN NaN
3.0000 2.5000 4.5000 5.0000 9.5000 3.0000 2.5000
6.0000 21.0000 7.0000 NaN NaN NaN NaN
7.5000 34.5000 NaN NaN NaN NaN NaN
3.0000 6.0000 24.0000 NaN NaN NaN NaN
2.0000 22.0000 NaN NaN NaN NaN NaN
5.0000 37.0000 NaN NaN NaN NaN NaN
1.5000 5.5000 25.0000 NaN NaN NaN NaN
1.0000 1.0000 1.5000 23.5000 NaN NaN NaN];
data_class={
'g' 'gc' 'c' '' '' '' ''
'g' 'gc' 'c' 'gc' '' '' ''
'c' '' '' '' '' '' ''
'g' 'c' 'g' 'gc' 'c' 'g' 'c'
'g' 'gc' 'c' '' '' '' ''
'g' 'c' '' '' '' '' ''
'g' 'gc' 'c' '' '' '' ''
'g' 'c' '' '' '' '' ''
'g' 'c' '' '' '' '' ''
'gc' 'g' 'c' '' '' '' ''
'g' 'gc' 'g' 'c' '' '' '' };
figure(1),clf(1)
data(end+1,:)=NaN;
b={bar([1 2],data([1 end],:),'stacked')};
hold on
for k=2:(size(data,1)-1)
b{k}=bar([k-1 k],data([end k],:),'stacked');
end
for k=1:(size(data,1)-1)
for k2=1:size(data,2)
switch data_class{k,k2}
case 'g'
set(b{k}(k2),'FaceColor','g')
case 'c'
set(b{k}(k2),'FaceColor','b')
case 'gc'
set(b{k}(k2),'FaceColor','c')
end
end
end