rggplot2ggridgesridgeline-plot

Unable to colour jittered points in geom_density_ridges


I'm trying to colour specific points within a ridge plot, but the points I am trying to highlight aren't displayed nor are they in the legend. In this example I am trying to highlight the points with labels "X" and "Y" withing ridges based on groups "A" and "B", but the points associated with "X" aren't plotted.

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)

A ggplot with geom_density_ridges

I was expecting the points associated with subgroup "X" to be plotted as points in a different colour and for subgroup "X" to appear in the legend.


Solution

  • You need to explicitly define the group, then it works:

    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
    

    Created on 2022-04-06 by the reprex package (v2.0.1)