How can I change the color of each stack in stacked bar plot?
45 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Gustav Modric
am 5 Nov. 2017
Bearbeitet: Gustav Modric
am 5 Nov. 2017
%Create a stacked bar
h = bar(X,'stacked');
% Set bar colors
set(h,{'FaceColor'},{'g';'r'});
Andres Mendez
am 22 Jul. 2020
An example with my data
barra = bar(1:1:20, cuentas3, 'stacked')
barra(1).FaceColor = 'c'
barra(2).FaceColor = 'y'
0 Kommentare
Alvin Barbier
am 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!
0 Kommentare
Siehe auch
Kategorien
Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!