Applying Labels to Stacked Bar Graph with Non-scalar X-axis Values
3 views (last 30 days)
Show older comments
I have a stacked bar graph (see below) with an x-axis consisting of dates. I'm familiar with the text function to apply data labels to each bar, however this funciton only accepts scalar values as input arguments. How can I create individual labels for each stacked bar? Is there another function that exists for this purpose?
0 Comments
Answers (1)
Shivam
on 28 Sep 2023
As per my understanding, you want to create individual labels for each stacked bar.
In order to do so, you need to deal with each stacked bar individually.
You can follow the below workaround to create individual labels.
figure;
h = bar(data, 'stacked');
% Add labels for each segment of each stacked bar
for i = 1:numel(h)
xData = h(i).XData;
yData = h(i).YData;
for j = 1:numel(xData)
label = num2str(yData(j));
% Adjust the position of the label horizontally and vertically using xpos and ypos
xpos = xData(j);
if i==1
ypos = yData(j)/2;
else
prevH = h(1).YData(j);
for k=2:i-1
prevH = prevH + h(k).YData(j);
end
ypos = prevH + yData(j)/2;
end
if yData(j) ~= 0
text(xpos, ypos, label, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
end
end
Additionally, you can rotate the label content using "rotation" property of "text" function.
Please refer to the following documentation to know more about text function:
I hope this helps.
0 Comments
See Also
Categories
Find more on 2-D and 3-D 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!