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

3 次查看(过去 30 天)
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.

采纳的回答

Adam Danz
Adam Danz 2020-8-31
编辑:Adam Danz 2020-8-31
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by