Custom Colors for Stacked Bar Chart

218 views (last 30 days)
Nicole Xu
Nicole Xu on 28 Jul 2020
Edited: Adam Danz on 3 Aug 2020
This is my current stacked chart. How do I changed the color of each section? So for example for the first bar "Con" I would like the red and blue section to be one color, the blue and green to be another and the middle orange and purple to be a third color. In addition would I be able to do that for each bar?

Answers (1)

Adam Danz
Adam Danz on 28 Jul 2020
Edited: Adam Danz on 3 Aug 2020
Set the FaceColor property to Flat and then define the colormap which specifies the color for each segment.
Here are two demos
For stacked bar plots, it will look something like this,
bh = bar(rand(3,6),'stacked');
set(bh, 'FaceColor', 'Flat')
bh(1).CData = [0 0 1]; % Change color to first level
bh(2).CData = [0 1 0]; % Change color to second level, etc...
To set all colors in 1 line after setting FaceColor to Flat,
colors = mat2cell(jet(numel(bh)),ones(numel(bh),1), 3);
set(bh, {'CData'}, colors) % using jet colormap
% or to assign pairs of colors,
colors = repelem(mat2cell(jet(numel(bh)/2),ones(numel(bh)/2,1), 3),2,1); % requires even number of objects in bh
set(bh, {'CData'}, colors)

Community Treasure Hunt

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

Start Hunting!