1

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?

4

1 回答 1

2

不是超级漂亮,但您可以制作一个 df/tibble 来描述 a geom_segment()for each year / id 组合的参数。您可能需要进行一些调整来清理显示的区域(就像coord_cartesian()我在这里所做的那样),但它可能会满足您的需要。

在此处输入图像描述

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))
于 2021-07-06T01:21:59.200 回答