如何用密度图叠加线图? (R,ggplot2)

时间:2015-07-09 08:54:22

标签: r ggplot2

您如何在一个图表中重叠以下曲线?任何帮助都表示赞赏。谢谢!

library(ggplot2)

x = -10:10
y = dnorm(x, mean=0, sd=3)
df.norm = data.frame('x'=x, 'y'=y)

ggplot(data=df.norm, aes(x=x, y=y)) +
        geom_line() +
        geom_point()

random = data.frame('x'=rnorm(1000, mean = 0, sd = 3))

ggplot(random, aes(x=x)) + 
        geom_density(size=1)

我尝试了以下内容并且它没有工作

ggplot(data=df.norm, aes(x=x, y=y)) +
        geom_line() +
        geom_point() +
        geom_density(random, aes(x=x), size=1)

1 个答案:

答案 0 :(得分:6)

library(ggplot2)

x = -10:10
y = dnorm(x, mean=0, sd=3)
df.norm = data.frame('x'=x, 'y'=y)

random = data.frame('x'=rnorm(1000, mean = 0, sd = 3))

ggplot() +
  geom_line(data=df.norm, aes(x=x, y=y)) +
  geom_point(data=df.norm, aes(x=x, y=y)) +
  geom_density(data=random, aes(x=x), size=1)

enter image description here