How do I label the grouped horizontal bars in MATLAB?
Show older comments
I know someone uses the text function but I am ont able to solve my problem. This is my code:
label = categorical({'A';'B';'C';'D';'E'});
risks = [-1,2;-1.5,1;-5,2.5;-5,NaN;-3.2,NaN;];
temp = abs(risks);
lim_g = max(max(temp));
h = barh(label,risks,'grouped');
set(h(1),'FaceColor',[0.753 0 0])
set(h(2),'FaceColor','g')
xlim([-lim_g-1 lim_g+1])
a=[cellstr(num2str(get(gca,'xtick')'))];
pct = char(ones(size(a,1),1)*'%');
new_yticks = [char(a),pct];
set(gca,'xticklabel',new_yticks)
I would like to put the value on the end of each bar. Can Someone help me? Many thanks!!!!
Accepted Answer
More Answers (1)
dpb
on 28 Jun 2017
I don't have HG2 so can't test and the solution to find the bar positions that worked with HG1 does not work with HG2. Contribtor Efstathios Zavvos added to an Answer the following based on a hidden property '[X/Y]Offset' that returns the position of the bar relative to the axis tick for each bar group.
His sample for a normal bar is below; hopefully will get you going...
Y=random('unif',0,100,[4 3]);
h=bar(Y);
yb = cat(1, h.YData);
xb = bsxfun(@plus, h(1).XData, [h.XOffset]');
for i = 1:size(yb,2)
for j = length(yb(:,1))
text(xb(j, i),yb(j, i), cellstr(num2str(Y(i, j))), 'rotation', 90);
end
end
NB: Add your request for the enhancement to be able to do this with builtin properties -- it's near criminal TMW didn't do this 20 yr ago; it's a routine expectation for any decent graphing tool.
Categories
Find more on Discrete Data Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!