Axis Customisation R (Space/Segmentation/Width/Subsetting)

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)) 

One way to create space between subsets is to use facet_wrap. In the example below, a column named subset is added to Dat, and the vars values are mapped to the "baseline" or "six months" cases. Then, the ggplot code is condensed by specifying subset as the facet variable, eliminating the need to specify new data for each geom.

I don't think this example gets to your final outcome, but I hope it provides some ideas on how to get there.

Dat <- y |> 
  mutate(across(everything(), as.character)) |> 
  pivot_longer(everything(), names_to = "var") |>
  mutate(subset = ifelse(var == 'baseline', 'baseline subset', 'six months subset'))

ggplot(Dat, aes(y = var)) +
  coord_flip() +
  geom_bar(aes(fill = value), position = "fill") +
  scale_fill_brewer(palette = "Dark2", guide = guide_legend(order = 2)) +
  new_scale_fill() +
  facet_wrap(~subset, ncol = 2, scales = 'free_x')

Thank you @scottyd22. Really appreciate your help in this instance :slight_smile:

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.