如何将 geom_segment 添加到 geom_density_ridges_gradient?

How to add geom_segment to geom_density_ridges_gradient?

我想在直方图显示自定义分位数的脊线图中添加垂直线段。

如果我用 ..x.. 映射填充颜色,我设法得到了垂直线段。但我想在密度图中显示分位数。我写了下面的代码:

library(datasets)
library(ggplot2)
data("iris")

iris_lines <- data.frame(Species = c("setosa", "versicolor", "virginica"),
                         x0 = c(5, 5.9, 6.5))

Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species, fill=(..quantile..))) +
  geom_density_ridges_gradient(jittered_points = FALSE, calc_ecdf = TRUE, quantile_lines = c(TRUE), quantiles =c(0.1,0.25,0.75,0.9),scale=0.9, color='white')+
  geom_segment(data = iris_lines, aes(x = x0, xend = x0, y = as.numeric(Species), yend = as.numeric(Species) + c(.9,.5,.5)), color = "red") + scale_y_discrete(expand = c(0.01, 0))
Figure1

如果我将填充颜色映射为 fill = ..x..,代码就会工作 我得到三个垂直线,代表每个密度图的平均值;但是,如果我将填充颜色映射为 fill = ..quantile..,则会出现以下错误:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 1, 3

漂亮的图表!

inherit.aes = F 添加到第二个几何对象,这样它就不会尝试将您的数据与 ggplot(aes() 调用中的填充计算相匹配。

Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species, fill=(..quantile..))) +
      geom_density_ridges_gradient(jittered_points = FALSE, 
                                   calc_ecdf = TRUE, 
                                   quantile_lines = c(TRUE), 
                                   quantiles =c(0.1,0.25,0.75,0.9),
                                   scale=0.9, color='white') +
      geom_segment(data = iris_lines, 
                   aes(x = x0, xend = x0, 
                       y = as.numeric(Species), yend = as.numeric(Species) + c(.9,.5,.5)),
                   color = "red", inherit.aes = F) +   #### HERE ####
      scale_y_discrete(expand = c(0.01, 0))
Figure1


编辑:

OP 在评论中询问有关选择性地标记某些元素并为中线添加标签的问题。这是一种方法,可能不是最简单的方法。

Figure1 <- ggplot(iris, aes(x=Sepal.Length, y=Species, 
                            fill = (..quantile..), 
                            color = (..quantile..))) +
  geom_density_ridges_gradient(jittered_points = FALSE, 
                               calc_ecdf = TRUE, 
                               quantile_lines = c(TRUE), 
                               quantiles =c(0.1,0.25,0.75,0.9),
                               scale=0.9, color='white') +
  geom_segment(data = iris_lines, 
               aes(x = x0, xend = x0, fill = "median",
                   y = as.numeric(Species), 
                   yend = as.numeric(Species) + c(.9,.5,.5),
                   color = "median")) +   #### HERE ####
  scale_y_discrete(expand = c(0.01, 0)) +

  scale_color_manual(name = "quantile",
                     limits = c(1:3, "median"),
                     values = alpha("firebrick1", c(0, 0, 0, 1)),
                     labels = c("<10%", "10-25%", "IQR", "median")) +
  scale_fill_manual(name = "quantile",
    limits = c(1:3, "median"),
    values = c("cadetblue", "coral", "orange", "white"), 
    na.value = "gray30",
    labels = c("<10%", "10-25%", "IQR", "median"))
Figure1