2016-11-29 33 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()