draw line on geom_density

by bison2178   Last Updated September 27, 2018 00:26 AM

I am trying to draw a line through the density plots from ggridges

library(ggplot2)
library(ggridges)
ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01)

Indicating the highest point and label the value of x at that point. Something like this below. Any suggestions on accomplishing this is much appreciated

enter image description here



Answers 1


This is not the most direct route (!), but one fun option is to interrogate the ggplot object itself and use it to construct additional features.

# This is the OP chart
library(ggplot2)
library(ggridges)
gr <- ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01)  

# Examine the calculations ggplot did to prepare the figure,
#   and pull some of them into a new table
ingredients <- ggplot_build(gr)
density_tbl <- data_frame(
  x = ingredients[["data"]][[1]][["x"]],
  y = ingredients[["data"]][[1]][["density"]],
  grp = ingredients[["data"]][[1]][["group"]],
  ymin = ingredients[["data"]][[1]][["ymin"]],
  iscale = ingredients[["data"]][[1]][["iscale"]],
  scale = ingredients[["data"]][[1]][["scale"]]
  )

# Pick the highest point. Could easily add quantiles or other features here.
density_lines <- density_tbl %>%
  group_by(grp) %>%
  filter(y == max(y)) %>%
  ungroup()

# Use the highest point to add more geoms
ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01) +
  geom_segment(data = density_lines, 
               aes(x = x, y = ymin, xend = x, yend = ymin+y*scale*iscale)) +
  geom_text(data = density_lines, 
            aes(x = x, y = ymin + 0.5 *(y*scale*iscale),
                label = round(x, 2)),
            hjust = -0.2)

enter image description here

Jon Spring
Jon Spring
September 27, 2018 00:06 AM

Related Questions



geom_desnity Error in R

Updated January 11, 2018 16:26 PM



3D surface with a 2D projection using R

Updated November 07, 2018 01:26 AM