R ggplot2防止vline出现在空的ggridge facet中

R ggplot2 Prevent vline from appearing in empty ggridge facet

我正在尝试生成多面脊线图,其中一些脊线是空的。下面的代码产生了一个例子。

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)

此处的垂直线贯穿第 2 方面没有数据的年份。 2003年后如何预防和制止?

不是很漂亮,但是您可以制作一个 df/tibble 来描述每个年份/id 组合的 geom_segment() 的参数。您可能需要进行一些调整以清理显示的区域(就像我在此处所做的 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))