Search code examples
rggplot2ggridgesridgeline-plot

Plotting normal distributions in a ridgeline plot with ggridges


I'm a little embarrassed to ask this question but I've spent the better part of my work day trying to find a solution, yet and here I am...

What I'm aiming for is a simple ridgeline plot of several normal distributions which are calculated from given means and SDs in my data, like in this example:

case_number    caseMean    caseSD
case1          0           1
case2          1           2
case3          3           3

All the examples I've found are working with series of measurement, like in the example with the temperatures in Lincoln, NE: Example of ridgeline plot https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html and I cannot get them to work.

As to my experience with R, I am not a complete idiot when it comes to data analysis but proper visualization is something I am eager to learn but unfortunately I need a solution to my problem rather.

Thank you very much for your help!


Solution

  • Edit -- added precise theoretical answer.

    Here's a way using dnorm to construct exact normal curves to those specifications:

    library(tidyverse); library(ggridges)
    n = 100
    df3 <- df %>%
      mutate(low  = caseMean - 3 * caseSD, high = caseMean + 3 * caseSD) %>%
      uncount(n, .id = "row") %>%
      mutate(x    = (1 - row/n) * low + row/n * high, 
             norm = dnorm(x, caseMean, caseSD))
    ggplot(df3, aes(x, case_number, height = norm)) +
      geom_ridgeline(scale = 3)
    

    enter image description here


    Similar to Sada93's answer, using dplyr and tidyr:

    library(tidyverse); library(ggridges)
    n = 50000
    df2 <- df %>% 
      uncount(n) %>%
      mutate(value = rnorm(n(), caseMean, caseSD))
    ggplot(df2, aes(x = value, y = case_number)) + geom_density_ridges()
    

    enter image description here

    sample data:

    df <- read.table(
      header = T, 
      stringsAsFactors = F,
      text = "case_number    caseMean    caseSD
    case1          0           1
    case2          1           2
    case3          3           3")