ggplot2 中的“+”运算符和 magrittr 中的“%>%”运算符有什么区别?

What is the difference between the "+" operator in ggplot2 and the "%>%" operator in magrittr?

ggplot2中的"+"运算符和magrittr中的"%>%"运算符有什么区别?

有人告诉我它们是相同的,但是如果我们考虑以下脚本。

library(magrittr)
library(ggplot2)

# 1. This works
ggplot(data = mtcars, aes(x=wt, y = mpg)) + geom_point()

# 2. This works
ggplot(data = mtcars) + aes(x=wt, y = mpg) + geom_point()

# 3. This works
ggplot(data = mtcars) + aes(x=wt, y = mpg) %>% geom_point()

# 4. But this doesn't
ggplot(data = mtcars) %>% aes(x=wt, y = mpg) %>% geom_point()

管道与ggplot2的添加有很大不同。管道运算符 %>% 所做的是获取左侧的结果并将其作为右侧函数的第一个参数。例如:

1:10 %>% mean()
# [1] 5.5

完全等同于mean(1:10)。管道对于替换多重嵌套函数更有用,例如

x = factor(2008:2012)
x_num = as.numeric(as.character(x))
# could be rewritten to read from left-to-right as
x_num = x %>% as.character() %>% as.numeric()

但这在 What does %>% mean in R? 中有很好的解释,您应该仔细阅读它以获取更多示例。

利用这些知识,我们可以将您的管道示例重写为嵌套函数,并看到它们仍然做同样的事情;但现在(希望)很明显为什么 #4 不起作用:

# 3. This is acceptable ggplot2 syntax
ggplot(data = mtcars) + geom_point(aes(x=wt, y = mpg))

# 4. This is not
geom_point(aes(ggplot(data = mtcars), x=wt, y = mpg))

ggplot2 包含一个用于 ggplot 对象的特殊 "+" 方法,它用于向绘图添加图层。直到你问你的问题,我才知道它也适用于 aes() 函数,但显然它也被定义了。这些都是在ggplot2内专门定义的。 + 在 ggplot2 中的使用早于管道,虽然用法相似,但功能却大不相同。

作为一个有趣的旁注,Hadley Wickham(ggplot2 的创建者)said that:

...if I'd discovered the pipe earlier, there never would've been a ggplot2, because you could write ggplot graphics as

ggplot(mtcars, aes(wt, mpg)) %>%
  geom_point() %>%
  geom_smooth()