rggridges

plot continuous geom_density_ridges with conditional fill color


I am trying to plot some density ridge plots, and have most of the plot complete, but when I use a conditional fill ... the output is divided into a density plot per fill color rather than a continuous density plot with alternating fill, which I want.

library(tidyverse)
library(ggridges)

tibble(
    A = rnorm(4e3, 0, .25),
    B = rnorm(4e3, 0.2, .25),
    C = rnorm(4e3, 0.4, .25),
) |>
pivot_longer(
    everything(),
    names_to = 'recipe',
    values_to = 'values'
) |>
ggplot(aes(x = values, y = recipe, fill = values > 0)) +
  geom_density_ridges(rel_min_height = 0.005) +
  scale_y_discrete(expand = c(0.01, 0)) +
  scale_x_continuous(expand = c(0.01, 0)) +
  theme_ridges()

enter image description here


Solution

  • Like this?

    library(tidyverse)
    library(ggridges)
    
    tibble(
      A = rnorm(4e3, 0, .25),
      B = rnorm(4e3, 0.2, .25),
      C = rnorm(4e3, 0.4, .25),
    ) |>
      pivot_longer(
        everything(),
        names_to = 'recipe',
        values_to = 'values'
      ) |>
      ggplot(aes(x = values, y = recipe, fill = factor(after_stat(x) > 0))) +
      geom_density_ridges_gradient(rel_min_height = 0.005) +
      scale_y_discrete(expand = c(0.01, 0)) +
      scale_x_continuous(expand = c(0.01, 0)) +
      theme_ridges() +
      labs(fill = "Values > 0")
    #> Picking joint bandwidth of 0.0426
    

    Created on 2024-03-21 with reprex v2.1.0