ggplot facet_wrap with specific order of variables in each facet

最后都变了- 提交于 2019-12-10 11:06:44

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/42112100/ggplot-facet-wrap-with-specific-order-of-variables-in-each-facet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!