How to add gaussian curve to histogram created with qplot?

后端 未结 2 1838
心在旅途
心在旅途 2020-12-09 20:30

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=         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 21:08

    ggplot2 uses a different graphics paradigm than base graphics. (Although you can use grid graphics with it, the best way is to add a new stat_function layer to the plot. The ggplot2 code is the following.

    Note that I couldn't get this to work using qplot, but the transition to ggplot is reasonably straighforward, the most important difference is that your data must be in data.frame format.

    Also note the explicit mapping of the y aesthetic aes=aes(y=..density..)) - this is slighly unusual but takes the stat_function results and maps it to the data:

    library(ggplot2)
    data <- data.frame(V1 <- rnorm(700), V2=sample(LETTERS[1:7], 700, replace=TRUE))
    ggplot(data, aes(x=V1)) + 
      stat_bin(aes(y=..density..)) + 
      stat_function(fun=dnorm) + 
      facet_grid(V2~.)
    

    enter image description here

提交回复
热议问题