4

I am trying to superimpose a normal distribution to a density using ggplot in R:

ggplot(Data, aes(x=Rel, y=..density..)) +
    geom_density(aes(fill=factor(cut)), position="stack") +
    stat_function(fun = dnorm, args = list(mean = Rel.mean, sd = Rel.sd))

But I keep getting this error:

Error in eval(expr, envir, enclos) : object 'density' not found
Calls: print ... <Anonymous> -> as.data.frame -> lapply -> FUN -> eval

Why? Any solution?

Medical physicist
  • 2,510
  • 4
  • 34
  • 51
  • 2
    You will get an answer easier if you provide a small [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – alko989 Jul 11 '14 at 12:34
  • 1
    See the comments on [this question](http://stackoverflow.com/questions/5688082/ggplot2-overlay-histogram-with-density-curve). The error is likely because you set a global y instead of setting y in `geom_density`. – aosmith Jul 11 '14 at 18:00
  • without data and a MWE, this question is not useful. – PatrickT May 17 '16 at 06:30

1 Answers1

6

Following @aosmith advice:

ggplot(Data, aes(x=Rel)) +
    geom_density(aes(y=..density.., fill=factor(cut)), position="stack") +
    stat_function(fun = dnorm, args = list(mean = Rel.mean, sd = Rel.sd))

Works!

Medical physicist
  • 2,510
  • 4
  • 34
  • 51
  • 3
    without data and a MWE, this answer is not useful. Please provide something along the lines of ``ggplot(data = mtcars, aes(x = factor(cyl))) + geom_density(aes(y = ..density.., fill = factor(gear)), position = "stack") + stat_function(fun = dnorm, args = list(mean = mean, sd = sd))`` – PatrickT May 17 '16 at 06:31
  • and a screenshot of the plot would be even better. – PatrickT May 17 '16 at 06:32