MATLAB: How to assign a label to each bar in stacked bar graph

bar labellingstacked bar

I am trying to represent how job are assigned to different machines. Machines are represented as x-axis in stacked bar graph and job process time are the bars in the stacked bar graph. I want to label the bars to show which job the bar is representing. Can you please tell me or show me how to label the graph or alternatives.
Here is a scenario of my problem: Lets say I have 4 Jobs {J1 J2 J3 J4} and they been assigned to two machines {M1 M2} using list scheduling. Form the algorithm, let say Jobs J1 and J3 will be assigned to M1 and J2 and J4 assigned to M2. Now I will use stacked bar graph to represent how jobs been assigning to the machines. Now, i want to assign label to each bar individually or some sort of function that assign label to each bar then it would be great. Thanks in advance 🙂

Best Answer

I am not exactly certain what you want, so you may have to experiment with this:
D = randi(10, 5, 3);
figure(1)
hBar = bar(D, 'stacked');
xt = get(gca, 'XTick');
set(gca, 'XTick', xt, 'XTickLabel', {'Machine 1' 'Machine 2' 'Machine 3' 'Machine 4' 'Machine 5'})
yd = get(hBar, 'YData');
yjob = {'Job A' 'Job B' 'Job C'};
barbase = cumsum([zeros(size(D,1),1) D(:,1:end-1)],2);
joblblpos = D/2 + barbase;
for k1 = 1:size(D,1)
text(xt(k1)*ones(1,size(D,2)), joblblpos(k1,:), yjob, 'HorizontalAlignment','center')
end
produces this plot: