使用美元符号表示法($)将变量与facet_grid()或facet_wrap()一起传递给aes()时出现问题

Chr*_*oph 14 r ggplot2 r-faq

我正在ggplot2做一些项目的分析,偶然我偶然发现一些(对我来说)奇怪的行为,我无法解释.当我写aes(x = cyl, ...)这个情节时,如果我使用相同的变量,它看起来会有什么不同aes(x = mtcars$cyl, ...).当我删除facet_grid(am ~ .)两个图表时再次相同.下面的代码是在我的项目中生成相同行为的代码之后建模的:

library(dplyr)
library(ggplot2)

data = mtcars

test.data = data %>%
  select(-hp)


ggplot(test.data, aes(x = test.data$cyl, y = mpg)) +
  geom_point() + 
  facet_grid(am ~ .) +
  labs(title="graph 1 - dollar sign notation")

ggplot(test.data, aes(x = cyl, y = mpg)) +
  geom_point()+ 
  facet_grid(am ~ .) +
  labs(title="graph 2 - no dollar sign notation")
Run Code Online (Sandbox Code Playgroud)

这是图1的图片:

图1  - 美元符号表示法

这是图2的图片:

图2  - 没有美元符号表示法

我发现我可以使用aes_string而不是aes将变量名称作为字符串传递来解决这个问题,但我想理解为什么ggplot表现得那样.在类似的尝试中也会出现问题facet_wrap.

对于任何提前帮助都很有帮助!如果我不理解,我会感到非常不舒服......

bap*_*ste 32

TL;博士

切勿使用[$内部使用aes().


考虑这个说明性示例,其中构面变量f有意地相对于非显而易见的顺序x

d <- data.frame(x=1:10, f=rev(letters[gl(2,5)]))
Run Code Online (Sandbox Code Playgroud)

现在对比这两个图的情况,

p1 <- ggplot(d) +
  facet_grid(.~f, labeller = label_both) +
  geom_text(aes(x, y=0, label=x, colour=f)) +
  ggtitle("good mapping") 

p2 <- ggplot(d) +
  facet_grid(.~f, labeller = label_both) +
  geom_text(aes(d$x, y=0, label=x, colour=f)) +
  ggtitle("$ corruption") 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

通过查看每个面板由ggplot2内部创建的data.frame,我们可以更好地了解发生的情况,

 ggplot_build(p1)[["data"]][[1]][,c("x","PANEL")]

    x PANEL
1   6     1
2   7     1
3   8     1
4   9     1
5  10     1
6   1     2
7   2     2
8   3     2
9   4     2
10  5     2

 ggplot_build(p2)[["data"]][[1]][,c("x", "PANEL")]

    x PANEL
1   1     1
2   2     1
3   3     1
4   4     1
5   5     1
6   6     2
7   7     2
8   8     2
9   9     2
10 10     2
Run Code Online (Sandbox Code Playgroud)

第二个绘图具有错误的映射,因为当ggplot为每个面板创建data.frame时,它会以"错误"顺序选择x值.

发生这种情况是因为使用了$断开要映射的各种变量之间的链接(ggplot必须假设它是一个独立的变量,它知道它可能来自任意的,断开连接的源).由于此示例中的data.frame不是根据因子排序的f,因此每个面板内部使用的子集data.frames假定顺序错误.

  • 此问题已在[`ggplot2 v3.0.0.9000`]中修复(https://github.com/tidyverse/ggplot2/pull/2694) (2认同)