Overlaying many curves from dnorm function

Hello. I have a tibble with unique pairs of parameters - in this case mean and standard deviation for a normal distribution. I would like to overlay the resultant normal curves for all the pairs on a single plot. For a single curve, I would do something like follows:

library(tidyverse)

param_tbl <- tibble(mean = c(5, 4, 6, 4, 3, 5, 6, 7),
            sd   = c(1, 2, 3, 2, 1, 3, 2, 2))

#data for a single curve with one pair of parameters
b <- tibble(x = seq(-5, 25, length.out = 100),
            y = dnorm(x, 5, 1))

#plot for single curve
b %>% ggplot(aes(x = x, y = y)) +
  geom_line()

How can I extend to plot all pairs?

Hi @tw0handt0uch,

I would use purrr to achieve this, check this out:

library(tidyverse)

param_tbl <- tibble(mean = c(5, 4, 6, 4, 3, 5, 6, 7),
                    sd   = c(1, 2, 3, 2, 1, 3, 2, 2))

param_tbl <-
param_tbl %>% 
  mutate(data = purrr::map2(mean, sd, 
                            ~tibble(x = seq(-5, 25, length.out = 100),
                                    y = dnorm(x, .x, .y)))) %>% 
  unnest(data)


param_tbl %>% 
  ggplot(aes(x, y, col = factor(mean), linetype = factor(sd))) +
  geom_line() +
  labs(col = 'Mean',
       linetype = 'SD')

Created on 2020-01-14 by the reprex package (v0.3.0)

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.