Bar chart colors depending on their value

(in MATLAB 2014a)
I would like to plot visuals to verify if a set of data complies with the requirements values.
req = [10,5,3];
data=[9,6,3];
To plot the following bar chart I used:
bar(req,0.5)
newXticklabel = {'label1','label2','label3'};
set(gca,'XtickLabel',newXticklabel);
hold on
bar(data,0.25,'g')
hold off
My question is: how do I change the color of one bar in red if the data is lower than the requirement value ?

 Accepted Answer

Try this:
req = [10,5,3];
data=[9,6,3];
hb1 = bar(req,0.5);
newXticklabel = {'label1','label2','label3'};
set(gca,'XtickLabel',newXticklabel);
hold on
hb2 = bar(data,0.25,'g');
barcomp = hb2.YData < hb1.YData; % Logical Vector Identifying Bar
newbar = bar(hb2.XData(barcomp), hb2.YData(barcomp), hb2.BarWidth, 'r'); % Overplot In Red
hold off

4 Comments

Hi nice try but it doesn't work
(>> barcomp = hb2.YData < hb1.YData;
Attempt to reference field of non-structure array.)
Indeed, hb1 and hb2 are double when I run your code. Maybe I should have mentionned that I use MATLAB 2014a (not sure if it changes anything though)
It changes everything! ‘HG2’ (Handle Graphics 2) was introduced in R2014b.
I no longer have access to R2014a (with ‘HG1’), so this may turn out to be iterative.
Try this version:
req = [10,5,3];
data=[9,6,3];
hb1 = bar(req,0.5);
newXticklabel = {'label1','label2','label3'};
set(gca,'XtickLabel',newXticklabel);
hold on
hb2 = bar(data,0.25,'g');
hb1XData = get(hb1, 'XData');
hb2XData = get(hb2, 'XData');
hb1YData = get(hb1, 'YData');
hb2YData = get(hb2, 'YData');
hb2BarWidth = get(hb2, 'BarWidth');
barcomp = hb2YData < hb1YData; % Logical Vector Identifying Bar
newbar = bar(hb2XData(barcomp), hb2YData(barcomp), hb2BarWidth, 'r'); % Overplot In Red
hold off
That does the same thing, using the get function to retrieve the data.
It works! Thanks :)
As always, my pleasure!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!