EpsilonDelta
EpsilonDelta

Reputation: 133

Multiple Layers in 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.

Upvotes: 3

Views: 196

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76641

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

Upvotes: 1

Related Questions