change color for specifics bars

조회 수: 1 (최근 30일)
Rachele Franceschini
Rachele Franceschini 2022년 3월 29일
답변: Dave B 2022년 3월 29일
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;

채택된 답변

Dave B
Dave B 2022년 3월 29일
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);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Title에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by