I have a plot that I would like to segment into 'baseline' and '6-months'
- 6 months variables are labelled x1/x2
- baseline is self-titled.
I would like to customise the plot so that:
- there is separation/space between two subsets (baseline + six months)
- And potentially so that the two subsets have different bar widths.
Would appreciate any ideas on how to encode this in R and the types of packages used.
Thanks.
library(ggplot2)
library(ggnewscale)
x1 = rep(1:3, times = 2)
x2 = rep(c("Y", "N"), each = 3)
baseline = rep(0:1, times = 3)
y <- data.frame(x1,x2,baseline)
Dat <- y |>
mutate(across(everything(), as.character)) |>
pivot_longer(everything(), names_to = "var")
ggplot(Dat, aes(y = var)) +
coord_flip() +
geom_bar(data = ~subset(.x, var %in% c("x1")), aes(fill = value), position = "fill") +
scale_fill_viridis_d(option = "B", guide = guide_legend(order = 3))+
new_scale_fill() +
geom_bar(data = ~subset(.x, var %in% c("x2")), aes(fill = value), position = "fill") +
scale_fill_brewer(palette = "Dark2", guide = guide_legend(order = 2)) +
new_scale_fill() +
geom_bar(data = ~subset(.x, var %in% c("baseline")), aes(fill = value), position = "fill") +
scale_fill_brewer(palette = "Paired", guide = guide_legend(order = 1))