필터 지우기
필터 지우기

Colored error bar plot with X axis labels

조회 수: 10 (최근 30일)
Dirk
Dirk 2018년 8월 12일
편집: dpb 2018년 8월 13일
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