Applying Labels to Stacked Bar Graph with Non-scalar X-axis Values
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Shivam
2023-9-28
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!