Normalizing y-axis in histograms in R ggplot to proportion

后端 未结 4 953
轮回少年
轮回少年 2020-11-29 17:23

I have a very simple question causing me to bang my head on the wall.

I would like to scale the y-axis of my histogram to reflect the proportion (0 to 1) that each b

相关标签:
4条回答
  • 2020-11-29 18:03

    As of the latest and greatest ggplot2 version 3.0.0, the format has changed. Now you can wrap the y value in stat() rather than messing with .. stuff.

    ggplot(mydataframe, aes(x = value)) +
      geom_histogram(aes(y = stat(count / sum(count))))
    
    0 讨论(0)
  • 2020-11-29 18:12

    Note that ..ncount.. rescales to a maximum of 1.0, while ..count.. is the non scaled bin count.

    ggplot(mydataframe, aes(x=value)) +
      geom_histogram(aes(y=..count../sum(..count..)))
    

    Which gives:

    enter image description here

    0 讨论(0)
  • 2020-11-29 18:22

    As of ggplot2 0.9, many of the formatter functions have been moved to the scales package, including percent_format().

    library(ggplot2)
    library(scales)
    
    mydataframe <- data.frame(name = c("A", "B", "C", "D"),
                              value = c(0.0000354, 0.00768, 0.00309, 0.000123))
    
    ggplot(mydataframe) + 
      geom_histogram(aes(x = value, y = ..ncount..)) +
      scale_y_continuous(labels = percent_format())
    
    0 讨论(0)
  • 2020-11-29 18:30

    I just wanted to scale the axis, to divide the y-axis by 1000, so I did:

    ggplot(mydataframe, aes(x=value)) +
      geom_histogram(aes(y=..count../1000))
    
    0 讨论(0)
提交回复
热议问题