change color for specifics bars

1 view (last 30 days)
Rachele Franceschini
Rachele Franceschini on 29 Mar 2022
Answered: Dave B on 29 Mar 2022
I have this code to create bar plot. but I would like to change color for specifics bars.
On the base of index, I would like that data with index (in xlabel) < 16 have to be red, >16 green, <5 blu and index ==16 green and ==8 blu
How can I do?
%Order table
z = sortrows(table,'variable','ascend');
%X
x = z.variable;
idxx=(1:20)'
x=z.variable(idxx)
%Y
y= z.variable1;
idxy=(1:20)'
y=z.variable1(idxy)
M2=[x y]
h=bar(idxx,M2(:,2))
h.FaceColor='flat';
xticks(1:numel(x))
xticklabels(x)
hAx=gca;
hAx.XTickLabelRotation=0;
%target
labels = categorical(z.textvariable);
xt = get(gca, 'XTick');
set(gca,'xticklabel',x)
text(xt, y, labels, 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
%title
title('title')
xlabel('labelx','FontSize',14)
ylabel('labely','FontSize',14)
%legend
legend({'name',},'Location','northeast','Orientation','vertical')
lgd = legend;
lgd.FontSize = 14;

Accepted Answer

Dave B
Dave B on 29 Mar 2022
I didn't fully understand your explanation of which colors you want where, but really all you have to do is set CData as you like it - there's one row for each bar and the columns a red, green, and blue (ranging from 0 to 1):
x = (1:20)';
y = rand(20,1);
h=bar(x,y);
h.FaceColor='flat';
ind = 1:20;
redind = ind < 16 & ind >=5;
greenind = ind >= 16;
blueind = ind < 5 | ind == 8;
h.CData(redind, :) = repmat([1 0 0],sum(redind),1);
h.CData(greenind, :) = repmat([0 1 0],sum(greenind),1);
h.CData(blueind, :) = repmat([0 0 1],sum(blueind),1);

More Answers (0)

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!