Jon Snow
Jon Snow

Reputation: 329

ggplot facet_wrap with specific order of variables in each facet

I would like to plot these data with ggplot:

library(ggplot2)
set.seed(0)
df <- data.frame(
  var1 = rep(c("group1", "group2"), each = 3),
  var2 = rep(letters[1:3], 2),
  value = runif(6, 0, 10)
)

The plot should be faceted like this:

pl <- ggplot(df, aes(var2, value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl

The order of var2 on the x-axis should be determined by increasing order of value. I could achieve this doing:

df$temp_var <- paste(df$var1, df$var2)
pl <- ggplot(df, aes(reorder(temp_var, value), value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl

However, x-axis labels should be a, b and c. Normally, I would convert var2 to a factor with the factor levels having the order I want, but in that case this is probably not possible. Anybody having any ideas how this can be done? :)

Upvotes: 3

Views: 1745

Answers (1)

Axeman
Axeman

Reputation: 35177

Just set the axis labels to be different than the actual breaks with a named character vector:

pl + scale_x_discrete(labels = setNames(as.character(df$var2), df$temp_var))

enter image description here

Upvotes: 7

Related Questions