Plotting histogram with percentage

11 views (last 30 days)
Thinkboard
Thinkboard on 6 Jul 2020
Commented: Adam Danz on 8 Jul 2020
Hi all,
Recently I had a csv that I want to import by
T = readtable('1.csv');
and plot by histogram
Any chance to display this histogram with indivudual percentage over each bar?
Class; Value; Class start; Class end;
1;8410;-0.039916738868;-0.032423677233;
2;78271;-0.032423677233;-0.024930615599;
3;501926;-0.024930615599;-0.017437553965;
4;149453;-0.017437553965;-0.009944492330;
5;342924;-0.009944492330;-0.002451430696;
6;546900;-0.002451430696;0.005041630939;
7;537726;0.005041630939;0.012534692573;
8;527320;0.012534692573;0.020027754207;
9;478488;0.020027754207;0.027520815842;
10;345973;0.027520815842;0.035013877476;
11;276272;0.035013877476;0.042506939111;
12;694253;0.042506939111;0.050000000745;

Answers (1)

Rik
Rik on 6 Jul 2020
You will have to insert those labels with the text function.
  6 Comments
Rik
Rik on 8 Jul 2020
You can either use the code Adam suggested, or look into what that function from the FEX is actually doing:
function histogramPercentage(x,fontSize)
h = histogram(x,'Visible', 'off');
[nelements,centers]= hist(x,h.NumBins);
percantages = 100 * nelements / sum(nelements);
bar(centers,nelements,'Facecolor',[0.4,0.7,0.9],'BarWidth',1);
for k = 1:numel(centers)
if percantages(k) ~= 0
text(centers(k),nelements(k),[sprintf('%.f',(percantages(k))) '%'],'HorizontalAlignment','center','VerticalAlignment','bottom','FontSize',fontSize);
end
end
So in short: you need the bin centers and the height. Then you can easily create the text objects in a loop.

Sign in to comment.

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!