无法为 geom_density_ridges 中的抖动点着色

Unable to colour jittered points in geom_density_ridges

我正在尝试为脊图中的特定点着色,但我试图突出显示的点未显示,也不在图例中。在此示例中,我试图突出显示带有基于组“A”和“B”的山脊的标签“X”和“Y”的点,但未绘制与“X”关联的点。

library(tidyverse)
library(ggridges)

data <- tibble(y = 1:10,
       group = as.factor(rep(c("A", "B"), each=5)),
       subgroup = as.factor(rep(c("X", rep("Y", each=4)),times=2)))

data%>% 
  ggplot(aes(x = y, y= group, fill = group))+
  geom_density_ridges(alpha=0.5)+
  geom_density_ridges(aes(point_fill = subgroup, point_color = subgroup), 
                      alpha=0, colour = NA, jittered_points = T, point_alpha=1)

我期待与子组“X”关联的点被绘制为不同颜色的点,子组“X”出现在图例中。

您可以通过将 group 美学添加到第二个 geom_density_ridges 来实现您想要的结果,即将 group = group 添加到 aes。

library(tibble)
library(ggplot2)
library(ggridges)

set.seed(123)

data <- tibble(
  y = 1:10,
  group = as.factor(rep(c("A", "B"), each = 5)),
  subgroup = as.factor(rep(c("X", rep("Y", each = 4)), times = 2))
)

ggplot(data, aes(x = y, y = group)) +
  geom_density_ridges(aes(fill = group), alpha = 0.5) +
  geom_density_ridges(aes(point_color = subgroup, group = group),
    alpha = 0, colour = NA, jittered_points = T, point_alpha = 1
  )
#> Picking joint bandwidth of 0.974
#> Picking joint bandwidth of 0.974

您需要显式定义组,然后才有效:

library(dplyr)
library(ggplot2)
library(ggridges)

data <- tibble(y = 1:10,
       group = as.factor(rep(c("A", "B"), each=5)),
       subgroup = as.factor(rep(c("X", rep("Y", each=4)),times=2)))
data%>% 
  ggplot(aes(x = y, y= group, group=group, fill = group))+
  geom_density_ridges(alpha=0.5)+
  geom_density_ridges(aes(point_fill = subgroup, point_color = subgroup), 
                      alpha=0, colour = NA, jittered_points = T, point_alpha=1)
#> Picking joint bandwidth of 0.974
#> Picking joint bandwidth of 0.974

reprex package (v2.0.1)

于 2022-04-06 创建