Home > Enterprise >  Unable to colour jittered points in geom_density_ridges
Unable to colour jittered points in geom_density_ridges

Time:04-06

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.

CodePudding user response:

You could achieve your desired result by adding the group aesthetic to the second geom_density_ridges, i.e. add group = group to 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

CodePudding user response:

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)

  • Related