Applying Labels to Stacked Bar Graph with Non-scalar X-axis Values
1 回表示 (過去 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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/859925/image.png)
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!