代码之家  ›  专栏  ›  技术社区  ›  Bogaso

在ggplot的直方图中添加正态密度图

  •  0
  • Bogaso  · 技术社区  · 9 月前

    这是我上一篇文章的后续问题 Plotting 2 histogram on top and bottom part of a single plot

    我在下面画了一对直方图

    library(ggplot2)
    set.seed(1)
    dat = rbind(data.frame('val' = rnorm(100), 'met' = 'Metric1'), data.frame('val' = rt(100, 2), 'met' = 'Metric12'))
    
    ggplot(dat, aes(x = val, fill = met)) + 
      geom_histogram(data    = dat[dat$met == 'Metric1',], 
                     breaks  = seq(-10, 10, 0.5),
                     mapping = aes(y = after_stat(density)),
                     colour  = "black",
                     alpha   = 0.3) +
      stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +
      geom_histogram(data    = dat[dat$met == 'Metric12', ],
                     breaks  = seq(-10, 10, 0.5),
                     mapping = aes(y = -after_stat(density)),
                     colour  = "black",
                     alpha   = 0.3)+
      coord_cartesian(xlim = c(-10, 10))
    

    有了这个,我就可以画画了 normal density plot 但不能覆盖第二直方图的正常密度曲线。

    有什么建议吗?我该怎么画第二张 正常密度图 因为第二个直方图会很棒。

    谢谢你的时间。

    1 回复  |  直到 9 月前
        1
  •  0
  •   Michiel Duvekot    9 月前
    ggplot() + 
      geom_histogram(data    = dat[dat$met == 'Metric1',], 
                     breaks  = seq(-10, 10, 0.5),
                     mapping = aes(x = val, y = after_stat(density)),
                     colour  = "black",
                     alpha   = 0.3) +
      geom_histogram(data    = dat[dat$met == 'Metric12', ],
                     breaks  = seq(-10, 10, 0.5),
                     mapping = aes(x = val, y = -after_stat(density)),
                     colour  = "black",
                     alpha   = 0.3)+
      coord_cartesian(xlim = c(-10, 10))+ 
      geom_line(
        aes(
          x = dat[dat$met == 'Metric1',]$val,
          y = dnorm(dat[dat$met == 'Metric1',]$val),
          color = as.factor(1))
      )+
      geom_line(
        aes(
          x = dat[dat$met == 'Metric12',]$val,
          y = -dnorm(dat[dat$met == 'Metric12',]$val),
          color = as.factor(2))
      )