Search code examples
rggplot2ggridgesridgeline-plot

Add custom vertical line joyplots ggridges


I would like to add a vertical line by row to joy plots using ggridges.

# toy example
ggplot(iris, aes(x=Sepal.Length, y=Species, fill=..x..)) +
geom_density_ridges_gradient(jittered_points = FALSE, quantile_lines = 
FALSE, quantiles = 2, scale=0.9, color='white') +
scale_y_discrete(expand = c(0.01, 0)) +
theme_ridges(grid = FALSE, center = TRUE)

I want to add a vertical line at 7 for virginica, 4 for versicolor, and 5 for setosa. Any ideas on how to do it?


Solution

  • Since your densities don't overlap, it may be easiest to just add additional segments.

    iris_lines <- data.frame(Species = c("setosa", "versicolor", "virginica"),
                             x0 = c(5, 4, 7))
    
    ggplot(iris, aes(x=Sepal.Length, y=Species, fill=..x..)) +
      geom_density_ridges_gradient(jittered_points = FALSE, quantile_lines = 
                                     FALSE, quantiles = 2, scale=0.9, color='white') +
      geom_segment(data = iris_lines, aes(x = x0, xend = x0, y = as.numeric(Species),
                                          yend = as.numeric(Species) + .9),
                   color = "red") +
      scale_y_discrete(expand = c(0.01, 0)) +
      theme_ridges(grid = FALSE, center = TRUE)
    

    enter image description here