Draw a vertical line at the intersect of two density plots

I would like to automatically draw a vertical line at the intersect of two geom_density() plots in ggplot() within geom_vline()?

data %>% 
  ggplot(aes(score, fill = actual_given_therapy)) +
  geom_density(alpha = 0.5) +
  geom_vline(xintercept = 3, color = "black") 

If I would know the two functions created by geom_density(), I guess it is possible to find the intersection with uniroot(), but is it even possible to extract them?

I want to show the theoretical threshold of a test visually.

Thank you for your help guys! :grinning_face_with_smiling_eyes:

1 Like

You can use layer_data() to extract the computed variables, as described e.g. here:


p <- tibble(score = c(rnorm(300, 3, 3), rnorm(300, 6, 3)),
       category = rep(c("a","b"), each = 300))|>
  ggplot(aes(score, fill = category)) +
  geom_density(alpha = 0.5)

computed_variables <- layer_data(p)

inversions <- computed_variables |>
  group_by(x) |>
  arrange(fill) |>
  mutate(delta_y = diff(y)) |>
  ungroup() |>
  pull(delta_y) |>
  sign() |>
  diff() |>
  (\(.x) which(.x != 0))() |>
  (\(.x) computed_variables$x[.x])()

p +
  geom_vline(xintercept = inversions,
             linetype = "dotted")

Created on 2021-11-17 by the reprex package (v2.0.1)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.