How to label histogram bars with data values or percents in R

前端 未结 2 1920
情歌与酒
情歌与酒 2020-12-07 14:52

I\'d like to label each bar of a histogram with either the number of counts in that bin or the percent of total counts that are in that bin. I\'m sure there must be a way to

相关标签:
2条回答
  • 2020-12-07 15:38

    To include the number of counts, you can just set labels=TRUE.

    The example below is just slightly adapted from one on the hist() help page:

    hist(islands, col="gray", labels = TRUE, ylim=c(0, 45))
    

    enter image description here

    Getting percentages is a bit more involved. The only way I know to do that it to directly manipulate the object returned by a call to hist(), as described in a bit more detail in my answer to this similar question:

    histPercent <- function(x, ...) {
       H <- hist(x, plot = FALSE)
       H$density <- with(H, 100 * density* diff(breaks)[1])
       labs <- paste(round(H$density), "%", sep="")
       plot(H, freq = FALSE, labels = labs, ylim=c(0, 1.08*max(H$density)),...)
    }
    
    histPercent(islands, col="gray")
    

    enter image description here

    0 讨论(0)
  • 2020-12-07 15:49

    Adding numbers at the tops of the bars in barplots or histograms distorts the visual interpretation of the bars, even putting the labels inside of the bars near the top creates a fuzzy top effect that makes it harder for the viewer to properly interpret the graph. If the number are of interest then this creates a poorly laid out table, why not just create a proper table.

    If you really feel the need to add the numbers then it is better to put them below the bars or along the top margin so that they line up better for easier comparison and don't interfere with the visual interpretation of the graph. Labels can be added to base graphs using the text or mtext functions and the x locations can be found in the return value from the hist function. Heights for plotting can be computed using the grconvertY function.

    0 讨论(0)
提交回复
热议问题