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

by Y Zhang   Last Updated January 13, 2018 00:26 AM

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)
Tags : r ggplot2


Answers 2


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

scoa
scoa
July 09, 2015 09:19 AM

ggplot2

A more concise version in ggplot2 using the argument inherit.aes = FALSE to overrides the default aesthetics used in the previous two layers.

library(ggplot2)
set.seed(2017)
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(data = df.norm, aes(x = x, y = y)) +
  geom_line() +
  geom_point() +
  geom_density(data = random,
               aes(x = x),
               inherit.aes = FALSE,
               size = 1)

enter image description here Base

Adapting the solution provided by scoa to the base package:

plot(df.norm, type = "l", bty = "n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd = 2)

enter image description here

Adding a legend, and a different colour for the density curve:

plot(df.norm, type = "l", bty="n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd =2, col = 'orange')
legend(x = "topleft", 
       c("df.norm", "Density plot"),
       col = c("black", "orange"),
       lwd = c(2, 2),
       bty = "n")

enter image description here

mpalanco
mpalanco
July 15, 2015 08:33 AM

Related Questions


R - How to find points within specific Contour

Updated May 28, 2015 23:11 PM

How to see the code of a stored plot (ggplot)

Updated May 29, 2015 01:11 AM

R ggplot remove certain items from legend

Updated April 03, 2015 23:11 PM

add second axis label

Updated April 10, 2015 23:11 PM

Error in facet_grid in ggplot2

Updated October 09, 2016 09:11 AM