rggplot2ggridges

R ggplot2 Prevent vline from appearing in empty ggridge facet


I'm trying to produce a faceted ridgeplot, where some ridges are empty. The code below produces an example.

library(ggridges)
library(tidyverse)

df <- tibble(x = rnorm(1000, 1, 1),
             id = c(rep(1, 600), rep(2, 400)),
             year = c(rep(2000:2005, each = 100), rep(2000:2003, each = 100)))
df %>%
  ggplot(aes(x = x, y = as.factor(year))) + 
    geom_density_ridges2() +
    facet_grid(.~id) +
    geom_vline(xintercept = 0)

ggridges problem example

The vertical line here stretches through the years in facet 2 for which there is no data. How can I prevent this and stop it after 2003?


Solution

  • Not super pretty, but you could make a df/tibble to describe parameters for a geom_segment() for each year / id combo. You'd likely need to include some tweaks to clean up the area shown (like with coord_cartesian() as I've done here) but it may serve for what you need.

    enter image description here

    library(ggridges)
    library(tidyverse)
    
    set.seed(123)
    
    df <- tibble(x = rnorm(1000, 1, 1),
                 id = c(rep(1, 600), rep(2, 400)),
                 year = c(rep(2000:2005, each = 100), rep(2000:2003, each = 100)))
    
    seg_df <-
      data.frame(
        x0 = 0,
        x1 = 0,
        id = c(rep(1, 6), rep(2, 4)),
        year = c(2000:2005, 2000:2003)
      ) %>%
      group_by(id) %>%
      arrange(year) %>%
      mutate(y0 = row_number(), y1 = y0 + 1) %>%
      mutate(y0 = ifelse(y0 == 1, -1, y0)) %>%
      mutate(y1 = ifelse(y1 == max(y1), y1 + 1, y1))
    seg_df
    
    df %>%
      ggplot(aes(x = x, y = as.factor(year))) + 
      geom_density_ridges2() +
      facet_grid(.~id) +
      geom_segment(
        data = seg_df,
        mapping = aes(
          x = x0,
          xend = x1,
          y = y0,
          yend = y1
        ),
        inherit.aes = FALSE
      ) + coord_cartesian(ylim = c(1, length(unique(df$year)) + 1.2))