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
bar can take third argument, which is color value, e.g. bar(x,y, 'r')
.
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
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
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)