How can I change the color of each stack in stacked bar plot?

76 views (last 30 days)
Hi,
I tried many ways to make this works. Unfortunately, I could not find any way. I have want to draw a stacked bar plot using barh and change the color of each stack individually, as I mentioned in the picture. For instance change the color of the first bar as black, blue, white, and so on. There is no specific pattern. Is it possible to make access each stack color? I warmly appreciate your help in advance.

Answers (3)

Gustav Modric
Gustav Modric on 5 Nov 2017
Edited: Gustav Modric on 5 Nov 2017
%Create a stacked bar
h = bar(X,'stacked');
% Set bar colors
set(h,{'FaceColor'},{'g';'r'});
  1 Comment
vahid farrahi
vahid farrahi on 8 Nov 2017
Thanks for your response. This does not work. The problem is that there is not a specific pattern for colors. In other words, one bar is for example red, blue, black. while the other one is black, red, blue. Using what you suggested all first stacks of ALL bars would be green and the second stacks of all bars would be red and so on(if there are more stacks)... But I want to control the color of each stack in each bar independently. I think the solution might be in CData (after matlab 2017b).

Sign in to comment.


Andres Mendez
Andres Mendez on 22 Jul 2020
An example with my data
barra = bar(1:1:20, cuentas3, 'stacked')
barra(1).FaceColor = 'c'
barra(2).FaceColor = 'y'

Alvin Barbier
Alvin Barbier on 9 Jan 2018
Hello Vahid,
I do not know if you found a solution to your problem but I had a similar issue and I found that post without the use of CData:
https://mathworks.com/matlabcentral/answers/354435-changing-color-of-individual-parts-of-stacked-bars#answer_279561
It is kind of tricky but helped me for my application. For your application I guess it should work even though having several classes will make the code a bit longer.
Below a "reduced" code of the example found in the link above:
data =[
8.5000 NaN NaN
3.0000 10.0000 NaN
5.0000 NaN NaN];
data_class={
'c' '' ''
'g' 'gc' ''
'c' '' ''};
data(end+1,:)=NaN;
figure;
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
Hope it will help!

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!