Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overlay a line plot with a density plot? (R, ggplot2)

Tags:

r

ggplot2

Hi how do I overlap the following curves in one graph? Any help's appreciated. Thank you!

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)

I tried the following and it didn't work

ggplot(data=df.norm, aes(x=x, y=y)) +
        geom_line() +
        geom_point() +
        geom_density(random, aes(x=x), size=1)
like image 658
YJZ Avatar asked Jun 20 '26 22:06

YJZ


1 Answers

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

like image 157
scoa Avatar answered Jun 23 '26 10:06

scoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!