Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Layers in ggplot2

Tags:

r

ggplot2

I want to overlay a plot of an empirical cdf with a cdf of a normal distribution. I can only get the code to work without using ggplot.

rnd_nv1 <- rnorm(1000, 1.5, 0.5)

plot(ecdf(rnd_nv1))
lines(seq(0, 3, by=.1), pnorm(seq(0, 3, by=.1), 1.5, 0.5), col=2)

For ggplot to work I would need a single data frame, for example joining rnd_vn1 and pnorm(seq(0, 3, by=.1), 1.5, 0.5), col=2). This is a problem, because the function rnorm gives me just the function values without values on the domain. I don't even know how rnorm creates these, if I view the table I just see function values. But then again, magically, the plot of rnd_nv1 works.

like image 372
EpsilonDelta Avatar asked Jan 01 '26 22:01

EpsilonDelta


1 Answers

The following plots the two lines but they overlap, since they are almost equal.

set.seed(1856)

x <- seq(0, 3, by = 0.1)
rnd_nv1 <- rnorm(1000, 1.5, 0.5)
dat <- data.frame(x = x, ecdf = ecdf(rnd_nv1)(x), norm = pnorm(x, 1.5, 0.5))

library(ggplot2)

long <- reshape2::melt(dat, id.vars = "x")

ggplot(long, aes(x = x, y = value, colour = variable)) +
  geom_line()

enter image description here

like image 80
Rui Barradas Avatar answered Jan 03 '26 19:01

Rui Barradas



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!