Sireat Conlien
Sireat Conlien

Reputation: 11

How to change bars colour in MATLAB

I am new to programming so I am learning introductory to MATLAB I was wondering how you could change colours of bar in MATLAB.

this is my script. Can someone please help!!

x =[1:8]
for y = [20 30 40 50 60 70 80]
bar(x,y)
if y < 40
col = 'b';
else if y > 40
col= 'g';
end
end
end

i also tried bar(x,y, r) but it doesnt work

Upvotes: 1

Views: 1481

Answers (3)

David
David

Reputation: 8459

Whilst this is overkill for your specific question, in general, to change the colour of bars depending on their height, you can apply a colormap to the bars. This is mainly from the bar documentation.

x = 1:8;
y = 10*x;
h=bar(y);  %// create a sample bar graph

For the colormap MAP, you do this:

colormap(MAP)
ch = get(h,'Children');
fvd = get(ch,'Faces');
fvcd = get(ch,'FaceVertexCData');
[zs, izs] = sort(y);
for i = 1:length(x)
    row = izs(i);
    fvcd(fvd(row,:)) = i;
end
set(ch,'FaceVertexCData',fvcd)
hold off

And, for example, using the builtin colormap hsv, you get enter image description here

But in this case we want a very specific colormap,

b=40 %// the cut-off for changing the colour
MAP=zeros(length(x),3); %// intialise colormap matrix
MAP(y<b,:)=repmat([0 0 1],sum(y<b),1); %// [0 0 1] is blue, when y<40
MAP(y>=b,:)=repmat([0 1 0],sum(y>=b),1); %// [0 1 0] is green, for y>=40
colormap(MAP)

which gives

enter image description here

Upvotes: 4

Luis Mendo
Luis Mendo

Reputation: 112659

To use two different colors depending on y: compute a logical index depending on y values and call bar twice with appropriate arguments:

x = [1:8];
y = [20 30 40 50 60 70 80];
ind = y < 40; %// logical index
bar(x(ind), y(ind), 'facecolor', 'b', 'edgecolor', 'k') %// blue bars, black edge
hold on %// keep plot
bar(x(~ind), y(~ind), 'facecolor', 'g', 'edgecolor', 'k') %// green bars, black edge
set(gca,'xtick',x)

enter image description here

Upvotes: 2

Marcin
Marcin

Reputation: 238101

bar can take third argument, which is color value, e.g. bar(x,y, 'r').

Upvotes: -1

Related Questions