R语言 ggh4x:使用guide_nested_axis在小平面图中将子组分组在一起

jvlzgdj9  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(209)

我想创建一个条形图,其中x轴的离散值将被分组到子组中(见下面的代码),当我已经在另一个变量上刻面时。我已经使用ggh4x来接近。但我还没有完全做到:

set.seed(9) 
dfx <- data.frame(
    x = rep(LETTERS[1:2], 50),
    Group = rep(c("Group 1", "Group 2", "Group 3"), c(33, 33, 34)),
    value = rpois(100, 10),
    facet_var = sample(rep(c("A", "B", "C", "D"),c(25,25,25,25)))
)

ggplot(dfx, aes(paste0(x, "&", Group), value)) +
    geom_col() +
    facet_wrap( ~ facet_var, ncol=2) +
    guides(x = ggh4x::guide_axis_nested(delim = "&"))

但我希望它将我的“Group”列分组在一起,以便它看起来更像我在这个示例中看到的:

df <- data.frame(
  x = LETTERS[1:16],
  group = rep(c("Group 1", "Group 2", "Group 3"), c(5, 3, 8)),
  value = rpois(16, 10)
)

ggplot(df, aes(paste0(x, "&", group), value)) +
  geom_col() +
  guides(x = ggh4x::guide_axis_nested(delim = "&"))

有人能帮忙吗?

xam8gpfp

xam8gpfp1#

使用interaction代替paste

library(ggh4x)
#> Loading required package: ggplot2
set.seed(9) 
dfx <- data.frame(
  x = rep(LETTERS[1:2], 50),
  Group = rep(c("Group 1", "Group 2", "Group 3"), c(33, 33, 34)),
  value = rpois(100, 10),
  facet_var = sample(rep(c("A", "B", "C", "D"),c(25,25,25,25)))
)

ggplot(dfx, aes(interaction(x, Group, sep = "&"), value)) +
  geom_col() +
  facet_wrap( ~ facet_var, ncol=2) +
  guides(x = ggh4x::guide_axis_nested(delim = "&"))

创建于2023-03-22带有reprex v2.0.2

相关问题