Changing colors in a stacked bar graph to specific ones?
23 views (last 30 days)
Show older comments
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 Comments
Answers (1)
David K.
on 22 Jul 2019
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 Comments
See Also
Categories
Find more on Graphics Performance 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!