Stacked Bar chart using structure, displaying putting values on each bar

4 views (last 30 days)
for x=1:20
y=[x,x+1,x+2,x+3];
bar(x,y,'stacked');
hold on;
end
Here, I want to set same color pattern in all the bars and want to put value of x in X axis and each individual y value in each sub-bar of stacked bar. Actually the values assigned to y are from 4 different array. I wanted to make the code simpler and so I remove array.
I wanted to use structure for y and draw bar chart outside the for loop, but I could not do it.
Additionally, I want to set the color pattern for every stacked bar same.
I have been stucked on this problem for a long time. I would really appriciate answer.

Accepted Answer

Adam Danz
Adam Danz on 31 Aug 2020
Edited: Adam Danz on 31 Aug 2020
To control the color of each segment, set FaceColor to Flat and use any colormap (from this answer).
Use text() and cumsum() to compute and write the bar heights.
cla()
hold on
for x=1:20
y=[x,x+1,x+2,x+3];
bh = bar(x,y,'stacked','FaceColor', 'Flat');
% Choose a color map (using "lines" in this example)
colors = mat2cell(lines(numel(bh)),ones(numel(bh),1), 3);
set(bh, {'CData'}, colors)
% Compute the height of each segment and write text to plot
text(repmat(x,1,numel(bh)), cumsum(y), compose('%.1f',cumsum(y)), 'Color', 'w', ...
'FontSize', 8, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top')
end

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!