在facet_grid中订购嵌套的facet标签 [英] Order nested facet labels in facet_grid

查看:113
本文介绍了在facet_grid中订购嵌套的facet标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图制作一个由三个不同变量构成的情节网格。我可以生成阴谋的网格很好,唯一的问题是标签放置的顺序看起来不合理。这是我正在做的一个简单的例子:

  library(ggplot2)
data(mtcars)
qplot(mpg,wt,data = mtcars)+ facet_grid(cyl + am〜vs,labeller = label_both)

产生下面的图:



现在,大多数情况下,情节看起来很棒,但是对于右侧的标签,我们可以看到cyl被标记为first(即接近情节)和 am 嵌套在外部,但是绘制情节的方式很明显,这些方面显示为嵌套在 cyl 中的



你的确可以使用贴标机按照alistaire的建议来解决这个问题。以下函数以相反的顺序调用标签数据框的列: label_both()

  label_rev<  -  function(labels,multi_line = TRUE,sep =:){
label_both(rev(labels),multi_line = multi_line,sep = sep)
}

然后导致期望的结果:

<$
code $ q


$ face $ g $ pre>


So, I am trying to make a grid of plots that are faceted by three different variables. I can generate the grid of plots just fine, the only hitch I am having is that the order in which the labels is placed seems out of order. Here is a simple example of what I am doing:

library(ggplot2)
data(mtcars)
qplot(mpg, wt, data=mtcars) + facet_grid(cyl +am ~ vs, labeller = label_both)

which produces the following plot:

Now, for the most part, the plot looks great, but for the labels on the right hand side, we see that cyl is labeled "first" (i.e. close to the plot) and am is nested outside, but the way the plot is laid out, it is clear that the facets are displayed with am nested within cyl.

So, I would like to change the order that the labels are listed so that am levels are listed within cyl levels to reflect the layout. I have tried to search for things like "facet_grid order labels" or "nested facet label order ggplot2", but almost all of the results I found had to do with changing the order of the actual levels of a given facet, rather than the problem I have described. Additionally, I looked into tinkering with the labeller, but that function seems to be called after the placement of the labels has been decided.

Thanks for your help!

解决方案

It seems that the ordering of the labels that you see is just the standard way how ggplot orders the labels. If you exchange the order of the variables in the formula, the labels also change position, but this at the same time also reorders the rows, which is probably not what you want:

qplot(mpg, wt, data=mtcars) +
    facet_grid(am + cyl ~ vs, labeller = label_both)

You can indeed use the labeller to fix this, as was suggested by alistaire. The following function calls label_both() with the columns of the label data frame in reversed order:

label_rev <- function(labels, multi_line = TRUE, sep = ": ") {
  label_both(rev(labels), multi_line = multi_line, sep = sep)
}

And it leads to the desired result:

qplot(mpg, wt, data=mtcars) +
    facet_grid(cyl + am ~ vs, labeller = label_rev)

这篇关于在facet_grid中订购嵌套的facet标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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