Home > Software engineering >  Creating dynamic x-axis labels when using facets
Creating dynamic x-axis labels when using facets

Time:12-02

I have a plot which uses facets as shown below:

library(tidyverse)

dat <- data.frame(grp = c("a", "a", "b", "b"),
           ep = c("r1", "r2", "r1", "r2"),
           val = c(3, 5, 2, 5),
           suffix = c("_w", "_x", "_y", "_z"))

dat %>% 
  ggplot(aes(x = ep, y = val, fill = ep))  
  geom_col(position = "dodge")   
  facet_wrap(~grp)

enter image description here

I would like to append the suffix column to each of the x-axis labels, so that end result would look like this:

enter image description here

I have tried this approach below, but it is saying that the suffix variable cannot be found:

dat %>% 
  ggplot(aes(x = ep, y = val, fill = ep))  
  geom_col(position = "dodge")   
  scale_x_discrete(labels = function(x) paste0(x, suffix))  
  facet_wrap(~grp)

CodePudding user response:

Don't do it within ggplot, create the suffix column first.

library(tidyverse)

dat <- data.frame(grp = c("a", "a", "b", "b"),
                  ep = c("r1", "r2", "r1", "r2"),
                  val = c(3, 5, 2, 5),
                  suffix = c("_w", "_x", "_y", "_z"))

dat %>% 
  mutate(x_suffix = paste0(ep, suffix)) %>%
  ggplot(aes(x = x_suffix, y = val, fill = ep))  
  geom_col(position = "dodge")   
  facet_wrap(~grp, scales = "free_x")

Created on 2021-12-01 by the reprex package (v2.0.1)

  • Related