MATLAB: How to color bars to correspond to their heights when using BAR3

barbar3colorcolormapheightMATLABvalue

Each column in a BAR or BAR3 plot is symbolized in a single color irrespective of the height of the bar itself. I would like MATLAB to color each bar with a color proportional to its height above the base plane.

Best Answer

The ability to color the bars to correspond to their heights is not available in MATLAB. The following pieces of code provide some useful workarounds:
Z = rand(5,5);
h = bar3(Z);
for i = 1:length(h)
zdata = get(h(i),'Zdata');
set(h(i),'Cdata',zdata)
end
An alternate workaround where the bars are shaded:
figure
h = bar3(Z);
shading interp
for i = 1:length(h)
zdata = get(h(i),'Zdata');
set(h(i),'Cdata',zdata)
set(h,'EdgeColor','k')
end
An alternate workaround where the bars can have solid colors uses this code:
Z = rand(8,3);
h = bar3(Z);
numBars = size(Z,1);
numSets = size(Z,2);
for i = 1:numSets
zdata = ones(6*numBars,4);
k = 1;
for j = 0:6:(6*numBars-6)
zdata(j+1:j+6,:) = Z(k,i);
k = k+1;
end
set(h(i),'Cdata',zdata)
end
Note that none of the above code fragments work with the BAR function, which creates barseries objects having somewhat different properties than the patch objects used by BAR3.