Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

r - How to add gaussian curve to histogram created with qplot?

I have question probably similar to Fitting a density curve to a histogram in R. Using qplot I have created 7 histograms with this command:

 (qplot(V1, data=data, binwidth=10, facets=V2~.)   

For each slice, I would like to add a fitting gaussian curve. When I try to use lines() method, I get error:

Error in plot.xy(xy.coords(x, y), type = type, ...) : 
plot.new has not been called yet

What is the command to do it correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried stat_function?

+ stat_function(fun = dnorm)

You'll probably want to plot the histograms using aes(y = ..density..) in order to plot the density values rather than the counts.

A lot of useful information can be found in this question, including some advice on plotting different normal curves on different facets.

Here are some examples:

dat <- data.frame(x = c(rnorm(100),rnorm(100,2,0.5)), 
                  a = rep(letters[1:2],each = 100))

Overlay a single normal density on each facet:

ggplot(data = dat,aes(x = x)) + 
  facet_wrap(~a) + 
    geom_histogram(aes(y = ..density..)) + 
    stat_function(fun = dnorm, colour = "red")

enter image description here

From the question I linked to, create a separate data frame with the different normal curves:

grid <- with(dat, seq(min(x), max(x), length = 100))
normaldens <- ddply(dat, "a", function(df) {
  data.frame( 
    predicted = grid,
    density = dnorm(grid, mean(df$x), sd(df$x))
  )
})

And plot them separately using geom_line:

ggplot(data = dat,aes(x = x)) + 
    facet_wrap(~a) + 
    geom_histogram(aes(y = ..density..)) + 
    geom_line(data = normaldens, aes(x = predicted, y = density), colour = "red")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...