Set the FaceColor property to Flat and then define the colormap which specifies the color for each segment.
Here are two demos
- https://www.mathworks.com/matlabcentral/answers/553894-barcharts-colours-based-on-other-vectors#answer_456622
- https://www.mathworks.com/matlabcentral/answers/486175-how-can-i-change-colors-and-generate-errorbars-in-a-bar-graph#answer_397071
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)