MATLAB: How to colorize individual bar in bar3

matlab graph

Hello.
I'm trying to plot 3D graph with bars, in which every bar is colored with color I choose. I found solution for 2D graphs:
Y=[ 1 2 3 ; 4 5 6 ; 3 4 5];
h = bar('v6',Y);
set(h(1),'facecolor','red') % use color name
set(h(2),'facecolor',[0 1 0]) % or use RGB triple
set(h(3),'facecolor','b') % or use a color defined in the help for PLOT
but i can't find out how to use this with bar3 function (use this on 3D). Has anyone any solution?

Best Answer

Never say never!
Y=[ 1 2 3 ; 4 5 6 ; 3 4 5];
h = bar3(Y);
cm = get(gcf,'colormap'); % Use the current colormap.
cnt = 0;
for jj = 1:length(h)
xd = get(h(jj),'xdata');
yd = get(h(jj),'ydata');
zd = get(h(jj),'zdata');
delete(h(jj))
idx = [0;find(all(isnan(xd),2))];
if jj == 1
S = zeros(length(h)*(length(idx)-1),1);
dv = floor(size(cm,1)/length(S));
end
for ii = 1:length(idx)-1
cnt = cnt + 1;
S(cnt) = surface(xd(idx(ii)+1:idx(ii+1)-1,:),...
yd(idx(ii)+1:idx(ii+1)-1,:),...
zd(idx(ii)+1:idx(ii+1)-1,:),...
'facecolor',cm((cnt-1)*dv+1,:));
end
end
rotate3d
Now S has the handle to each surface so you can change the color of each (or set any other individual property) as you wish. I.e, set(S(1),'facecolor','red'). Also, if you knew ahead of time how many surfaces there would be, you could create a matrix of colors and index into that as S was created....