Colored error bar plot with X axis labels

21 次查看(过去 30 天)
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

采纳的回答

dpb
dpb 2018-8-12
编辑:dpb 2018-8-13
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Properties 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by