MATLAB: How to explicitly change the colors of the bars in a stacked bar graph

barbarscdatacolorsdifferentexplicitfacecolorforgraphMATLABplotstacked

How to explicitly change the colors of the bars in a stacked bar graph?
I would like to create a bar plot with each bar of different color. For the example below, I want to have 9 different colors, instead of each column of the matrix having a different number.
Is it possible?
a = [1,3,6;2,5,6;8,2,1]
H=bar(a, 'stacked');

Best Answer

You can use the Color Data (CData) property for bar graph released in R2017b.
You can change the color for a particular bar by setting the FaceColor property to 'flat'. Then, change the corresponding row in the CData matrix to the new RGB triplet. Here is the link for the CData property in bar graph:
For example,
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.
Related Question