フィルターのクリア

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.
  1 件のコメント
Dirk
Dirk 2018 年 8 月 12 日
Thanks for that

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Object Properties についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by