How can I change the color of each stack in stacked bar plot?
35 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/167987/image.png)
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.
0 Commenti
Risposte (3)
Gustav Modric
il 5 Nov 2017
Modificato: Gustav Modric
il 5 Nov 2017
%Create a stacked bar
h = bar(X,'stacked');
% Set bar colors
set(h,{'FaceColor'},{'g';'r'});
Andres Mendez
il 22 Lug 2020
An example with my data
barra = bar(1:1:20, cuentas3, 'stacked')
barra(1).FaceColor = 'c'
barra(2).FaceColor = 'y'
0 Commenti
Alvin Barbier
il 9 Gen 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!
0 Commenti
Vedere anche
Categorie
Scopri di più su Line Plots in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!