1

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?
a11
  • 3,122
  • 4
  • 27
  • 66
  • The stat is not right; change it to `"ydensity"`. – Kat Oct 31 '22 at 18:28
  • @Kat doesn't that calculate the density from the column values? The probability density is already given, I don't need to calculate it, I want to plot what is given – a11 Oct 31 '22 at 19:55
  • 1
    I'm sorry. I thought you may have been looking for something different since you set `..density..` in `ggplot`. I added an answer. If you want it to look the same (just rotated), you need the same parameters. – Kat Oct 31 '22 at 21:12

1 Answers1

1

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

Kat
  • 15,669
  • 3
  • 18
  • 51