This is important to understand: When you dodge a bar, you split it into sub-bars whose aggregate width is the same as the original bar. That why the bar in panel 3 appears 4 times as wide (width is vertical here, as @nirgrahamuk points out) as the individual bars in panel 4..
On solution is to make sure each donor gets their own bar in each panel, sort of like this:
# data extracted from example, saved as toy_data
structure(list(NES = c(-0.8, 0.6, 0.45, 0.5, 0.4, 0.3), pathway = c("ED",
"AY", "RS", "RS", "RS", "RS"), donor = c("A", "C", "D", "C",
"B", "A"), group2 = c("P", "O", "P", "P", "P", "P")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L)) -> toy_data
toy_data
#> NES pathway donor group2
#> 1 -0.80 ED A P
#> 2 0.60 AY C O
#> 3 0.45 RS D P
#> 4 0.50 RS C P
#> 5 0.40 RS B P
#> 6 0.30 RS A P
# add new column that combines values of donor and pathway columns
library(tidyverse)
toy_data |>
mutate(donor_pathway = str_c(donor, '_', pathway)) -> toy_data
toy_data
#> # A tibble: 6 × 5
#> NES pathway donor group2 donor_pathway
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 -0.8 ED A P A_ED
#> 2 0.6 AY C O C_AY
#> 3 0.45 RS D P D_RS
#> 4 0.5 RS C P C_RS
#> 5 0.4 RS B P B_RS
#> 6 0.3 RS A P A_RS
# plot
toy_data |>
ggplot(aes(x = donor_pathway, y = NES, fill = donor)) +
geom_bar(stat = "identity", position = "dodge") +
facet_grid(pathway~group2,
scales = "free_y",
space = "free") +
guides(fill = guide_legend(reverse = TRUE)) +
theme_bw() %+replace%
theme(strip.text.y = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size = 12)) +
coord_flip()
Created on 2024-06-24 with reprex v2.0.2
Full reprex
structure(list(NES = c(-0.8, 0.6, 0.45, 0.5, 0.4, 0.3), pathway = c("ED",
"AY", "RS", "RS", "RS", "RS"), donor = c("A", "C", "D", "C",
"B", "A"), group2 = c("P", "O", "P", "P", "P", "P")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L)) -> toy_data
toy_data
#> NES pathway donor group2
#> 1 -0.80 ED A P
#> 2 0.60 AY C O
#> 3 0.45 RS D P
#> 4 0.50 RS C P
#> 5 0.40 RS B P
#> 6 0.30 RS A P
# add new column that combines values of donor and pathway columns
library(tidyverse)
toy_data |>
mutate(donor_pathway = str_c(donor, '_', pathway)) -> toy_data
toy_data
#> # A tibble: 6 × 5
#> NES pathway donor group2 donor_pathway
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 -0.8 ED A P A_ED
#> 2 0.6 AY C O C_AY
#> 3 0.45 RS D P D_RS
#> 4 0.5 RS C P C_RS
#> 5 0.4 RS B P B_RS
#> 6 0.3 RS A P A_RS
toy_data |>
ggplot(aes(x = donor_pathway, y = NES, fill = donor)) +
geom_bar(stat = "identity", position = "dodge") +
facet_grid(pathway~group2,
scales = "free_y",
space = "free") +
guides(fill = guide_legend(reverse = TRUE)) +
theme_bw() %+replace%
theme(strip.text.y = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size = 12)) +
coord_flip()
Created on 2024-06-24 with reprex v2.0.2