Jordan Wrong
Jordan Wrong

Reputation: 1245

Overlay a Normal Density Plot On Top of Data ggplot2

I plot a density curve using ggplot2. After I plot the data, I would like to add a normal density plot right on top of it with a fill.

Currently, I am using rnorm() to create the data but this is not efficient and would work poorly on small data sets.

library(tidyverse)

#my data that I want to plot
my.data = rnorm(1000, 3, 10)

#create the normal density plot to overlay the data
overlay.normal = rnorm(1000, 0, 5)

all = tibble(my.data = my.data, overlay.normal = overlay.normal)
all = melt(all)
ggplot(all, aes(value, fill = variable))+geom_density()

enter image description here

The goal would be to plot my data and overlay a normal distribution on top of it (with a fill). Something like:

ggplot(my.data)+geom_density()+add_normal_distribution(mean = 0, sd = 5, fill = "red)

Upvotes: 0

Views: 2150

Answers (2)

Jordan Wrong
Jordan Wrong

Reputation: 1245

I figured out the solution from mixing Jon's answer and an answer from Hadley.

my.data = rnorm(1000, 3, 10)

ggplot(my.data %>% enframe(), aes(value)) +
  geom_density(fill = "mediumseagreen", alpha = 0.1) +
  geom_area(stat = "function", fun = function(x) dnorm(x, mean = 0, sd = 5), fill = "red", alpha = .5) 

enter image description here

Upvotes: 2

Jon Spring
Jon Spring

Reputation: 66500

Here's an approach using stat_function to define a normal curve and draw it within the ggplot call.

ggplot(my.data %>% enframe(), aes(value)) +
  geom_density(fill = "mediumseagreen", alpha = 0.1) +
  stat_function(fun = function(x) dnorm(x, mean = 0, sd = 5),
                color = "red", linetype = "dotted", size = 1)

enter image description here

Upvotes: 3

Related Questions