Thanks @jrlewi, this does exactly what I described. Since your solution finds the density estimates outside of ggplot2, I had to have a play about because I have another factor which I use in facet_grid() (my fault for not mentioning it earlier
). Combined with what you wrote, I managed to find a solution, although not at all elegant:
library(tidyverse)
data <- data.frame(
x = c(rnorm(1000, mean = 1, sd = 1), rnorm(1000, mean = 0, sd = 1), rnorm(1000,mean = -1, sd = 0)),
group = c(rep('a', 1000), rep('b', 1000), rep('c', 1000))
)
# Get density information for each group
densities <- data %>%
group_by(group) %>%
do(., dens = density(.$x))
# Bind these into a data frame in order to plot them using ggplot2
densities_df <-
data.frame(
group = c(rep('a', 512),
rep('b', 512),
rep('c', 512)),
x = c(densities$dens[[1]]$x,
densities$dens[[2]]$x,
densities$dens[[3]]$x),
y = c(densities$dens[[1]]$y,
densities$dens[[2]]$y,
densities$dens[[3]]$y)
) %>%
mutate(
group = factor(group),
variable = case_when(
(x >= -2 & x <= 0) ~ "On",
(x >= 0.2 & x <= 1) ~ "Off",
TRUE ~ NA_character_
)
)
# Plot data
ggplot(densities_df, aes(x = x, y = y)) +
geom_area(data = filter(densities_df, variable == 'On'), fill = '#8ad5ae') +
geom_area(data = filter(densities_df, variable == 'Off'), fill = '#f8d0d2') +
geom_line(size = 1) +
facet_grid(.~group)

Created on 2018-11-13 by the reprex package (v0.2.1)
Now I need to figure out how to crowbar this into ggridges... think I'll grab some lunch first.