I would like to create a bar plot in which the discrete values of the x axis would be grouped into subgroups (see code below), when I have already faceted on another variable. I have used ggh4x to get me close. But I'm not quite there:
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 = "&"))
But would like it to group my "Group" column together so that it looks more like what I see in this example:
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 = "&"))
Anyone can help?
Use interaction
instead of 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 = "&"))
Created on 2023-03-22 with reprex v2.0.2