How can I color bars to correspond to their heights when using BAR3?
19 views (last 30 days)
Show older comments
MathWorks Support Team
on 12 Feb 2010
Commented: Jan
on 4 Apr 2016
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.
Accepted Answer
MathWorks Support Team
on 12 Feb 2010
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.
1 Comment
Jan
on 4 Apr 2016
Please remove the empty lines between the lines of code to improve the readability.
If the input data is a vector, the bars have all the same color. This occurs in R2011b (HG1) and R2015b (HG2).
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!