如何将多个曲线和曲线与R和ggplot结合?

时间:2019-03-01 08:27:01

标签: r ggplot2

我想通过在dnorm中绘制多条ggplot曲线来模拟色谱图,

ggplot(data.frame(x = 0), aes(x = x)) +
  mapply(function(mean, sd, col) {
    stat_function(fun = dnorm, args = list(mean = mean, sd = sd), col = col)
  },
  mean = c(0, 1, .5), 
  sd = c(1, .5, 2), 
  col = c('red', 'blue', 'green')) +
  xlim(-5, 5) +
  theme_classic()

Plotted separately

但是,我不想通过单独绘制来合并它们,而是通过对x轴上每个点的曲线求和(即dnorm(x, 0, 1) + dnorm(x, 1, 0.5) + dnorm(x, 0.5, 2),其中-5

Combined

我可以用数字方式执行此操作,但是如果可能的话,我更愿意使用stat_function()(或类似名称)。请告知。

1 个答案:

答案 0 :(得分:4)

ggplot(data.frame(x = 0), aes(x = x)) +
  stat_function(fun = function(x) rowSums(mapply(dnorm, mean = c(0, 1, .5), 
                                                 sd = c(1, .5, 2), MoreArgs = list(x = x)))) + 
  xlim(-5, 5) +
  theme_classic()

resulting plot