3

Context: I have some data, and I wish to:

  1. plot a histogram of them
  2. add a kernel density
  3. add a "theoretical density"
  4. add a legend to distinguish between 2. and 3.

Consider:

X <- rnorm(1000,0,1)
Y <- (X^2-1)/2
ggplot(as.data.frame(Y), aes(x=Y)) + 
    geom_histogram(aes(y=..density..),      
                   binwidth=.2,
                   colour="black", fill="white") +
    geom_density(alpha=.2, fill="#FF6666") 

enter image description here

This accomplishes 1. and 2., but how can I achieve 3. and 4.? I have written the function I wish to plot:

myfunc <- function(x) {
    2*exp(-x-0.5)/(sqrt(2*x+1)*sqrt(2*pi))
}

Any other comments/critiques are welcome (I am learning)

1
  • 1
    For (3) see stat_function, though the legend might require calculating both lines outside of ggplot and adding a geom_path layer manually, depending on how picky you are about the legend appearance. Commented Oct 13, 2012 at 23:45

1 Answer 1

4

Your custom function isn't terribly well behaved on that domain, so I substituted another simple one in, for illustration purposes.

#Dummy data set for the legend
dat <- data.frame(x = rep(NA_integer_,2),
                  y = rep(NA_integer_,2),
                  grp = c('Theoretical','Estimated'))
ggplot(as.data.frame(Y), aes(x=Y)) + 
    geom_histogram(aes(y=..density..),      
                   binwidth=.2,
                   colour="black", fill="white") +
    geom_density(alpha=.2, fill="#FF6666",color = '#FF6666') + 
    stat_function(fun = function(x) exp(-x),colour = "blue") + 
    geom_point(data = dat,aes(x = x,y = y,color = grp)) + 
    scale_color_manual(name = "",values = c('#FF6666','blue'))

enter image description here

I monkeyed with the colors somewhat, but you can tweak that as you see fit. There may be a cleaner way to do the legend, but the "data frame with NA's and a grouping variable" is sort of my standard method for this kind of thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.