How to place percent of each bar/bin of histogram on histogram chart in the code below?
40 次查看(过去 30 天)
显示 更早的评论
Hi all,
I have a code like this. Could you guys please help me to plot the percent of total for each histogram bar exactly on top of it? also, how to plot the mean in the middle of the chart instead of writing values manually for text command.
I really really appreciate your help.
histogram(Data,'BinEdges',edges,'Normalization','probability','FaceColor','#D95319','FaceAlpha',1); %, 'DisplayStyle','stairs'
ytix = get(gca, 'YTick'); % setting y in %
set(gca, 'YTick',ytix, 'YTickLabel',ytix*100);% setting y in %
MeanPlot = mean(Data);% calculating mean
text(4.5,0.4,(['mean = ',num2str(MeanPlot,3)])); % plotting mean on chart ; here I want to have that position exactly at the middle of the graph on top of the highest value
set(gca,'xtick',1:5,...
'xticklabel',{'Strongly disagree','Disagree','Neutral','Agree','Strongly agree'}); %creating x labels
ylabel('Percent (%)'); % y label
% set(findall(gcf,'-property','FontSize'),'FontSize',15);
title('Sample Chart for "Chartester"'); % title
0 个评论
采纳的回答
Scott MacKenzie
2021-6-6
Instead of histogram, I suggest you use histcounts along with bar:
% test data
data = rand(1,1000);
hc = histcounts(data);
b = bar(hc);
% percent of total for each bar
s = compose('%.1f%%', hc / sum(hc) * 100);
yOffset = 5; % tweat, as necessary
text(b.XData, b.YEndPoints + yOffset,s);
2 个评论
Scott MacKenzie
2021-6-6
Although there are more elegant, data-independent ways to do this, you can just put something like the following code after the bar function:
set(gca,'ylim', [0 150]); % make some room at the top
s1 = sprintf('Grand mean = %.3f', mean(data));
text(5.5, 140, s1); % choose y-coord to get proper positioning
更多回答(1 个)
Steven Lord
2021-6-6
Let's make some sample data and plot a histogram with a small number of bins.
x = randn(1, 1e4);
h = histogram(x, 'NumBins', 10);
I'm going to extract two of the histogram properties to their own variables to save on typing.
edges = h.BinEdges;
values = h.Values;
The center of each bin is its left edge plus half the distance to the right edge (which is where diff comes in.)
centers = edges(1:end-1)+diff(edges)/2;
Now let's put the text 10% above the top of each bin. You may want to tweak the actual y values, since the labels for the shortest bins will overlap the bins themselves.
text(centers, 1.1*values, string(values), 'HorizontalAlignment', 'center')
Adjust the limits of the axes to fit the highest bar's label.
ylim(ylim.*[1 1.15])
2 个评论
Steven Lord
2021-6-7
Specify the 'Normalization' name-value pair in your histogram call and you'd probably want to call sprintf instead of just string in the text call.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!