Multiple histograms with variable size binwidth in ggplot2

99封情书 提交于 2020-01-13 19:38:17

问题


Consider the following

d <- read.table(text="
        class     num  married type
    1     0.0   63530    23067    A
    2     2.5   27061    16601    A
    3     3.5   29938    19332    B
    4     4.5   33076    24112    A
    5     5.6   45759    32405    A
    6     6.5   72794    61234    A
    7     8.0  153177   107089    A
    8    10.8  362124   267303    A
    9    13.5  551051   334578    A
    10   15.5  198634   181530    A
    11    2.5   52710    10450    B
    12    7.0  123177    98076    B
    13    8.0  262524   105331    B
    14   13.5  301031   127690    B
    15   15.5  103634    49887    B
  ")

p <- ggplot(d) +
      geom_histogram(aes(x=class,weight=num,fill=type),
                     binwidth=6,alpha=.4) +
      geom_histogram(aes(x=class,weight=married,fill=type,position = "identity"),
                     binwidth=6) +
      facet_grid(~type)

This comes close to what I need. However, it would be better for me to have histograms with variable binwidth, and this proved to be more difficult than I expected. For example, I changed the script as follows

bins <- c(0,4,8,16)
p <- ggplot(d) +
      geom_histogram(aes(x=class,weight=num,fill=type),
                 breaks = bins,alpha=.4) +
      geom_histogram(aes(x=class,weight=married,fill=type,position = "identity"),
                 breaks = bins) +
      facet_grid(~type)

but in this case bars are note scaled properly - i.e. so that bar areas, not bar lengths, are proportional respectively to num and married. Note that adding y =..density.. does not solve the problem, as in this case histograms are not scaled according to numerosity. Any suggestion?

来源:https://stackoverflow.com/questions/19397894/multiple-histograms-with-variable-size-binwidth-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!