How to change color for stacked bar chart

Hi
I am wondering how I can change the color of the bars in a stacked bar chart. The code below gives me the error message "Expected one output from a curly brace or dot indexing expression, but there were 2 results." I wanted to apply blue \ hatch on the gray column, but so far I am not even able to change the color of the bars. I am able to make all bars in blue hatch \ with white background.
I have added a png to show what I want. I changed the colors in the png after running the script with the mouse, and therefor I do not have the option to export the figure as eps (better quality) with correct colors.
ba = bar(y,'stacked', 'FaceColor','flat');
ba.CData(1,:) = [0.5 0.5 0.5]
ba.CData(2,:) = [0 0 1]
applyhatch_plusC(gcf,'\','b');

 Accepted Answer

Try this:
y = [50 50; 25 75; 30 70];
figure
ba = bar(y,'stacked', 'FaceColor','flat');
ba(1).CData = [0.3 0.3 0.7];
ba(2).CData = [1 1 1]*0.8;
Experiment to get the result you want.

4 Comments

Yes!! Thank you so much! You do not know how to apply hatches as well? I do not know how to use the "applyhatch_plusC" function on only the upper part of the columns.
As always, my pleasure!
I am not familiar with the ‘applyhatch_plusC’ function. I did manage to get the x-coordinates of the bar edges (the ‘BL’ matrix):
XD = ba(2).XData;
BW = ba(2).BarWidth/2;
BL = [XD(:)-BW XD(:)+BW]; % Bar Limits
That is the best I can do. (The y-coordinates are the values of the ‘y’ matrix, and also the zero baseline.) IIf you have the Symbolic Math Toolbox, see if the MuPad plot:Hatch (link) function can do what you want.
Thanks again! For future people searching for a solution to what I have been trying: I was not able to make 'plot::Hatch' work, so I ended up using 'hatchfill2' which worked great, except for the legend. To make it work with the legend 'legendflex' can be used, but I was not able to achive what I wanted with positioning so I ended up using indesign to fix the legend.
As always, my pleasure!
Your Comment certainly argues for a function that combines all of those features.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Products

Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!