rggplot2ridgeline-plot

R vertical ridgeline plot, error on width and stat parameters


How can I reformat this ridgeline plot so that is a vertical ridgeline plot?

My real dataset is the actual PDF. For a minimum reproducible example, I generate distributions and extract the PDFs to use in a dummy function. The dataframe has a model name (for grouping), x values paired with PDF ordinates, and an id field that separates the different ridgeline levels (i.e., ridgeline y axis).

set.seed(123)
makedfs <- function(name, id, mu, sig) {
  
  vals <- exp(rnorm(1000, mean=mu, sd=sig))
  pdf <-density(vals)
  model <- rep(name, length(pdf$x))
  prox <- rep(id, length(pdf$x))
  df <- data.frame(model, prox, pdf$x, pdf$y)
  colnames(df) <- c("name", "id", "x", "pdf")
  
  return(df)
}

df1 <- makedfs("model1", 0, log(1), 1)
df2 <- makedfs("model2", 0, log(0.5), 2)
df3 <- makedfs("model1", 1, log(0.2), 0.8)
df4 <- makedfs("model2", 1, log(1), 1)

df <- rbind(df1, df2, df3, df4)

From this answer, R Ridgeline plot with multiple PDFs can be overlayed at same level, I have a standard joyplot:

ggplot(df, aes(x=x, y=id, height = pdf, group = interaction(name, id), fill = name)) +
  geom_ridgeline(alpha = 0.5, scale = .5) +
  scale_y_continuous(limits = c(0, 5)) +
  scale_x_continuous(limits = c(-6, 6))

enter image description here

I am trying the code below based on https://wilkelab.org/ggridges/reference/geom_vridgeline.html but it throws an error on the width parameter.

p <- ggplot(df, aes(x=id, y=x, width = ..density.., fill=id)) +
  geom_vridgeline(stat="identity", trim=FALSE, alpha = 0.85, scale = 2)

Error in `f()`:
! Aesthetics must be valid computed stats. Problematic aesthetic(s): width = ..density... 
Did you map your stat in the wrong layer?

Solution

  • If you wanted the same graph, just vertically oriented, you need to use the same parameters when you use geom_vridgeline.

    I swapped the limits you originally set so you can see that it's the same.

    ggplot(df, aes(x = id, y = x, width = pdf, fill = name,
                   group = interaction(name, id))) +
      geom_vridgeline(alpha = 0.85, scale = .5) +
      scale_x_continuous(limits = c(0, 5)) +         # <-- note that the x & y switched
      scale_y_continuous(limits = c(-6, 6))
    

    enter image description here