ggplot facet_wrap在每个方面的特定变量顺序 [英] ggplot facet_wrap with specific order of variables in each facet

查看:550
本文介绍了ggplot facet_wrap在每个方面的特定变量顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot绘制这些数据:

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

x轴上的 var2 的顺序应该由。我可以做到这一点:

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

但是,x轴标签应该是 a b c 。通常,我会将 var2 转换为具有我想要的顺序的因子级别的因子,但在这种情况下,这可能是不可能的。
任何人有任何想法如何做到这一点? :)

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

推荐答案

只需将轴标签设置为与具有命名字符向量的实际分隔符不同即可:

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

这篇关于ggplot facet_wrap在每个方面的特定变量顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆