How to display labels above a histogram bin?

前端 未结 3 627
暖寄归人
暖寄归人 2020-12-18 07:02

I have an array a(30,2) where the first column is a unique sample number and the second column is a value assigned to the sample. I plot a histogram of the 2nd

3条回答
  •  暖寄归人
    2020-12-18 07:13

    First, create a histogram using HISTC as suggested by @Itamar Katz. To make the bins the same as with HIST, you need to properly calculate bin edges. Then you can plot the distribution and add the labels using TEXT and NUM2STR.

    %# get the edges, bin centers
    nBins = 10;
    edges = linspace(min(a(:,2),max(a(:,2),nBins+1); %# edges go from minimum to maximum of distribution
    bins = (edges(1:end-1)+edges(2:end))/2;
    
    %# get the counts and the bin-index
    [counts,binIdx] = histc(a(:,2),edges);
    
    %# plot the counts and bins (not edges) with `bar`
    figure
    bar(bins,counts);
    
    %# Set the axes limits such that you have enough space for the labels
    ylim([0,2*max(counts)]);
    
    %# add the labels. Vertically align such that the text goes from the y-coordinate
    %# down (as opposed to being centered on the y-coordinate).
    for b = 1:nBins
        text(bins(b),counts(b)*2,num2str(a(b==binIdx,1)),'VerticalAlignment','top')
    end
    

提交回复
热议问题