将正态分布绘制到现有图中。

3
我有这个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")

但是我现在不知道如何将其添加到我的现有图表中。有人能帮我解决这个问题吗?


请使用SO格式并提供数据示例。 - timat
对不起...我不知道这是怎么回事... - Nadine_Golinelli
1
这个答案可能会帮助你入门。 - aosmith
1个回答

2

ggplot2提供了stat_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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接