Changing colors in a stacked bar graph to specific ones?
25 次查看(过去 30 天)
显示 更早的评论
Hello everyone! I am trying to change the colors of each individual bar in a stacked bar graph. This is what I have so far:
strains = categorical({'Strain 1','Strain 2','Strain 3','Strain 4','Strain 5'});
voltrange = [1000 600 200 100 100;...
900 300 400 300 100;...
1000 300 100 300 300;...
1000 400 300 100 200;...
1200 300 100 300 100]
voltscreening = barh(strains,voltrange,'stacked');
xlim([800 2300]);
So basically, I need to be able to change each individual section because the current colors that are there now actually do not correspond with each other. Is there a way I can do this? When I did some searching up I found this code that seemed to work:
a = [1,3,6;2,5,6;8,2,1];
H=bar(a, 'stacked');
colorSet = [];
for i = 1:3
myColors = round(rand(3,3),1);
colorSet = [colorSet myColors];
H(i).FaceColor = 'flat';
H(i).CData = myColors;
end
This will display the stacked bar plot with different colors.
But I'm not really sure of the specifics of how it works. Is there a way I can alter this code so that I can control what each bar color is instead of having random colors? Any help is appreciated, thanks!
0 个评论
回答(1 个)
David K.
2019-7-22
In order to figure out how that code works I'd suggest first adding a pause(1) before the end of the for loop. This way you can see what happens in each loop.
Next, create your own color matrix. it creates 3 3x3 random matrices so you need to create a 3x3x3 matrix and go through them.
myColors(:,:,1) = [.2 .3 .4; .5 .5 .5; 0 0 1];
myColors(:,:,2) = ...
From what I found going through it, each loop is another section of the bar starting from the bottom. Each column are the variables in [0,1] signifying percentages for RGB. Then each row is a different stacked bar.
So for your situation you would actually need a 5x3x5 matrix looping 5 times. In an example where the middle bar has the first two sections switched to could create the matrix as follows to switch the colors.
myColors(:,:,1) = [0 0 1; 0 1 0; 0 0 1];
myColors(:,:,2) = [0 1 0; 0 0 1; 0 1 0];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!