Bar graph comparison with custom x-axis and text

Hi All,
I want to compare two vectors using bar graph with custom labels and a text on top of each bar. Can you please help me with this? Below is the code i tried:
y1=[[0.41 0.38 0.42]];
y2=[[0.63 0.75 0.81]];
x=1:3;
figure(1)
bar(x,[y1' y2'])
label1={'front1';'front2';'front3'};%%corresponds to y1
label2={'back1';'back2';'back3'};%%corresponds to y2
So basically, i want label1 and label2 in the x-axis and corresponding values of y1,y2 on top of the bar.

 채택된 답변

Star Strider
Star Strider 2018년 1월 21일

1 개 추천

This will work for your two-variable problem:
y1=[[0.41 0.38 0.42]];
y2=[[0.63 0.75 0.81]];
x=1:3;
figure(1)
bar(x,[y1' y2'])
label1={'front1';'front2';'front3'};%%corresponds to y1
label2={'back1';'back2';'back3'};%%corresponds to y2
text(x, y1, label1, 'VerticalAlignment','bottom', 'HorizontalAlignment','right')
text(x, y2, label2, 'VerticalAlignment','bottom', 'HorizontalAlignment','left')
A more general approach:
labels = {label1; label2};
figure(1)
hBar = bar(x,[y1' y2']);
for k1 = 1:size(hBar,2)
ctr(k1,:) = bsxfun(@plus, hBar(1).XData, [hBar(k1).XOffset]');
ydt(k1,:) = hBar(k1).YData;
text(ctr(k1,:),ydt(k1,:), labels{k1}, 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
end

댓글 수: 4

Sowmya MR
Sowmya MR 2018년 1월 21일
편집: Sowmya MR 2018년 1월 21일
Hi, Thank you. However i want labels (label1, label2) in x-axis and values of corresponding vectors y1 and y2 (0.41, 0.63...) on top of the bar as text?
Try this:
y1=[[0.41 0.38 0.42]];
y2=[[0.63 0.75 0.81]];
y12 = {regexp(sprintf('%.2f\n',y1),'\n','split'); regexp(sprintf('%.2f\n',y2),'\n','split')};
x=1:3;
label1={'front1';'front2';'front3'};%%corresponds to y1
label2={'back1';'back2';'back3'};%%corresponds to y2
labels = {label1; label2};
figure(1)
hBar = bar(x,[y1' y2']);
set(gca, 'XtickLabel',[])
for k1 = 1:size(hBar,2)
ctr(k1,:) = bsxfun(@plus, hBar(1).XData, [hBar(k1).XOffset]');
ydt(k1,:) = hBar(k1).YData;
text(ctr(k1,:),ydt(k1,:), y12{k1}(1:end-1), 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
text(ctr(k1,:),-0.05*ones(size(x)), labels{k1}, 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
end
Experiment to get the result you want.
perfect.. thank you..
As always, my pleasure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Labels and Annotations에 대해 자세히 알아보기

질문:

2018년 1월 21일

댓글:

2018년 1월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by