ggplot facet_nested 删除子标题并仅保留分组标题

问题描述 投票:0回答:1

我有以下代码,可以创建带有子标题的绘图。

pdf <- data.frame(xx = as.factor(c(rep(0, 100), rep(1, 100))),
                  value = rnorm(200),
                  selected_site = c('y', rep('n', 98), 'y'),
                  name = as.factor(rep(1:5, each = 20)),
                  version = rep(c('A', 'B'), each = 100))


pdf %>%
  ggplot(aes(x = value, fill = xx)) +
  geom_histogram(alpha=0.6, position="identity") +
  facet_nested(version*selected_site ~ name, scale = 'free', ) +
  scale_fill_manual(name = '', values = c('red', 'blue')) +
  facetted_pos_scales(
    y = list(selected_site == TRUE ~ scale_y_continuous(limits = c(0,2), guide = "none"),
             selected_site == FALSE ~ scale_y_continuous(limits = c(0,15), guide = "none"))) +
  xlab('') + ylab('') +
  theme_bw() + theme(legend.position = 'none')

我想删除子标题“n”和“y”,只保留分组标题“A”和“B”。有办法做到吗?

ggplot2 nested header facet-wrap facet-grid
1个回答
0
投票

调整我对 facet_wrap2() 的答案,按两个变量分组,但用一个标签,您可以通过

strip
strip_nested
参数删除条带背景和文本。然而,这并不完美,因为它保留了一些空白空间。不幸的是,但我还没有找到摆脱它的选项:

library(ggplot2)
library(ggh4x)

set.seed(123)

pdf |>
  ggplot(aes(x = value, fill = xx)) +
  geom_histogram(alpha = 0.6, position = "identity") +
  facet_nested(version * selected_site ~ name,
    scale = "free",
    strip = strip_nested(
      by_layer_y = TRUE,
      background_y = list(
        element_rect(),
        element_blank()
      ),
      text_y = list(
        element_text(),
        element_blank()
      )
    )
  ) +
  scale_fill_manual(name = "", values = c("red", "blue")) +
  facetted_pos_scales(
    y = list(
      selected_site == "TRUE" ~ scale_y_continuous(limits = c(0, 2), guide = "none"),
      selected_site == "FALSE" ~ scale_y_continuous(limits = c(0, 15), guide = "none")
    )
  ) +
  xlab("") +
  ylab("") +
  theme_bw() +
  theme(legend.position = "none")

© www.soinside.com 2019 - 2024. All rights reserved.