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)
I would like to append the suffix column to each of the x-axis labels, so that end result would look like this:
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)