在geom_density_ridges上画线

时间:2018-09-26 23:13:32

标签: r ggplot2 density-plot

我试图通过ggridges的密度图画一条线

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

指示最高点,并在该点标记x的值。下面是这样的。对此的任何建议都将受到赞赏

enter image description here

1 个答案:

答案 0 :(得分:2)

一种简洁的方法是询问ggplot对象本身,并使用它来构建其他功能:

# 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)  

编辑:此部分已缩短,使用purrr::pluck提取列表的整个data部分,而不是手动指定以后需要的列。

# 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) 

enter image description here