draw line on geom_density_ridges

前端 未结 1 329
小蘑菇
小蘑菇 2021-01-15 04:17

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)) + 
  g         


        
相关标签:
1条回答
  • 2021-01-15 05:05

    One neat approach 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)  
    

    Edit: This next part has been shortened, using purrr::pluck to extract the whole data part of the list, instead of manually specifying the columns we'd need later.

    # Extract the data ggplot used to prepare the figure.
    #   purrr::pluck is grabbing the "data" list from the list that
    #   ggplot_build creates, and then extracting the first element of that list.
    ingredients <- ggplot_build(gr) %>% purrr::pluck("data", 1)
    
    # Pick the highest point. Could easily add quantiles or other features here.
    density_lines <- ingredients %>%
      group_by(group) %>% filter(density == max(density)) %>% 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+density*scale*iscale)) +
      geom_text(data = density_lines, 
                aes(x = x, y = ymin + 0.5 *(density*scale*iscale),
                    label = round(x, 2)),
                hjust = -0.2) 
    

    0 讨论(0)
提交回复
热议问题