2016-11-29 59 views
2

我有这个ggplot情节正态分布到现有的情节

ggplot(data = ph, aes(x = index1)) + geom_density() 

,我想补充一个正态分布,均值相等的(= 2.71)和标准偏差(= 0.61)

我创建的正态分布:

nd1 <- rnorm(n = 100000, mean = 2.71), sd = 0.61) 
nd1plot <- qplot(nd1, geom = "density") + theme_classic() + ggtitle("Normalverteilung") 

但现在我不知道如何将它添加到现有的情节。任何人都可以帮我解决这个问题吗?

+0

请使用SO格式化并提供数据例如 – timat

+0

对不起......我不知道这是如何制定出... –

+0

[这个答案](http://stackoverflow.com/a/ 29182589/2461552)可能会让你开始。 – aosmith

回答

0

ggplot2stat_function()这种事情,但我的解决方案采取更清晰的名称更手动的方法。你没有提供你的数据的例子,但你应该能够用你想要的任何列或向量替换mtcars$mpg

library(tidyverse) # Gives us ggplot2 and lots of other goodies 

# Choose your variable of interest 
dta <- mtcars$mpg %>% 
    as_tibble() # USing a tibble instead of a dataframe makes the data more predictable 

# Generate normal data based on dta 
norm_data <- 
    rnorm(
    n = length(dta), 
    mean = mean(dta$value), 
    sd = sd(dta$value) 
) 

# Create the plot 
ggplot(dta, aes(x = value)) + 
    geom_density() + 
    geom_density(aes(norm_data), color = "darkgray", linetype = "dashed") + 
    theme_classic()