MATLAB Answers

Dirk
0

Colored error bar plot with X axis labels

Asked by Dirk
on 12 Aug 2018 at 3:07
Latest activity Edited by dpb
on 13 Aug 2018 at 17:15
Accepted Answer by dpb

Hi Everyone, I am trying to create a bar graph with individually colored bars and also with error bars. However I cannot seem to get X axis labels under each bar. I have tried various suggestions from the Answers and File Exchange, but for some reason it's not working for me. Here are two scripts that I have tried (version 2016a):

% first try
X=[1 2 0.25; 2 3 0.55];
figure
bar(X(1,1),X(1,2),0.5,'FaceColor','b');
hold on
bar(X(2,1),X(2,2),0.5,'FaceColor','r');
hold on
errorbar(X(1:2,2),X(1:2,3),'LineStyle','none','Color','k');
set(gca,'XTickLabel',{'Light','Dark'});
X=[1 2 0.25; 2 3 0.55];
% Second try
figure
bar(X(1,1),X(1,2),0.5,'FaceColor','b');
hold on
bar(X(2,1),X(2,2),0.5,'FaceColor','r');
hold on
errorbar(X(1,1),X(1,2),X(1,3),'LineStyle','none','Color','k');
set(gca,'XTickLabel','Light');
hold on
errorbar(X(2,1),X(2,2),X(2,3),'LineStyle','none','Color','k');
set(gca,'XTickLabel','Dark');
hold on

Thanks

  0 Comments

Sign in to comment.

1 Answer

Answer by dpb
on 12 Aug 2018 at 14:23
Edited by dpb
on 13 Aug 2018 at 17:15
 Accepted Answer

The problem is that bar as you've used it draws only the one bar as an individual element so there aren't any ticks set for more than that one bar. Either try is close; but each has same problem... :)

X=[1 2 0.25; 2 3 0.55];
figure
bar(X(1,1),X(1,2),0.5,'FaceColor','b');
hold on
bar(X(2,1),X(2,2),0.5,'FaceColor','r');
errorbar(X(1:2,2),X(1:2,3),'LineStyle','none','Color','k');
set(gca,'XTick',[1 2];'XTickLabel',{'Light','Dark'});

Alternatively, you can use the facility to set colors on individual bars via the .CData property and set all the bars together--to make bar use the .CData you must set the 'FaceColor' property to 'flat'

hB=bar(X(:,1),X(:,2),0.5,'FaceColor','flat');  % bars; keep handle use flat
hB.CData(2,:)=[0.75 0.15 0];                   % set 2nd bar to a red hue
hAx=gca;
hAx.XTickLabel={'Light','Dark'};
hold on
hE=errorbar(X(:,1),X(:,2),X(:,3),'LineStyle','none','Color','k');

produces

ADDENDUM

Yet another alternative is to make the x-axis variable categorical...

C=categorical(X(:,1),[1 2],{'Light','Dark'});
hB=bar(C,X(:,2),0.5,'FaceColor','flat');

will then automagically label the x-ticks with the categorical variable labels; one swaps writing the xticklabel property explicitly with making the categorical variable.

  1 Comment

Thanks for that

Sign in to comment.