0
votes

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)
2
What exactly is your question?heds1
I edited in the question at the bottom.Jordan Wrong

2 Answers

3
votes

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

2
votes

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