How can I change the color of each stack in stacked bar plot?
45 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
Gustav Modric
2017-11-5
编辑:Gustav Modric
2017-11-5
%Create a stacked bar
h = bar(X,'stacked');
% Set bar colors
set(h,{'FaceColor'},{'g';'r'});
Andres Mendez
2020-7-22
An example with my data
barra = bar(1:1:20, cuentas3, 'stacked')
barra(1).FaceColor = 'c'
barra(2).FaceColor = 'y'
0 个评论
Alvin Barbier
2018-1-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!