R中的aes和aes_string(ggplot2)有什么区别

joa*_*oal 15 r ggplot2 aesthetics

随着失踪信息学背景有困难明白之间的差别aes,并aes_string在GGPLOT2及其对日常使用影响.

从描述(?aes_string)我能够理解两者describe how variables in the data are mapped to visual properties (aesthetics) of geom.

此外,它说,aes uses non-standard evaluation to capture the variable names.aes_string使用regular evaluation.

从示例代码可以看出,两者都产生相同的输出(a list of unevaluated expressions):

> aes_string(x = "mpg", y = "wt")
List of 2
 $ x: symbol mpg
 $ y: symbol wt
> aes(x = mpg, y = wt)
List of 2
 $ x: symbol mpg
 $ y: symbol wt
Run Code Online (Sandbox Code Playgroud)

Non-standard evaluationHadley Wickham在他的" 高级R "一书中描述了一种方法,它不仅可以调用函数参数的值,还可以调用生成它们的代码.

我会假设regular evaluation反对只调用函数中的值,但我没有找到确认这个假设的来源.此外,我不清楚这两者是如何不同的,以及为什么当我使用包装时这应该与我相关.

内部R网站上提到了这一点aes_string is particularly useful when writing functions that create plots because you can use strings to define the aesthetic mappings, rather than having to mess around with expressions.

但从这个意义上来说,我不明白为什么我应该使用aes而不是总是选择aes_string使用ggplot2......在这个意义上,它将帮助我找到对这些概念的一些澄清和日常使用的实际提示.

Rol*_*and 15

aes为您节省一些打字,因为您不需要引号.就这些.您当然可以随时使用aes_string.aes_string如果要以编程方式传递变量名,则应使用.

内部aes采用match.call了非标准的评价.这是一个简单的例子:

fun <- function(x, y) as.list(match.call())
str(fun(a, b))
#List of 3
# $  : symbol fun
# $ x: symbol a
# $ y: symbol b
Run Code Online (Sandbox Code Playgroud)

为了比较:

library(ggplot2)
str(aes(x = a, y = b))
#List of 2
# $ x: symbol a
# $ y: symbol b
Run Code Online (Sandbox Code Playgroud)

符号在稍后阶段进行评估.

aes_string使用parse以达到相同的:

str(aes_string(x = "a", y = "b"))
#List of 2
# $ x: symbol a
# $ y: symbol b
Run Code Online (Sandbox Code Playgroud)

  • “如果要以编程方式传递变量名称,则应使用 aes_string”不再正确,因为 ggplot 3.0.0 及其对 `!!` 的支持。请参阅 /sf/answers/3721801541/。 (3认同)
  • 不幸的是,这并不是那么简单:ggplot 没有相同的绘图行为,这取决于您使用的是 `aes` 还是 `aes_string`。它以不同的方式弄乱了内存并绘制了不同的东西......例如参见/sf/ask/1640748651/覆盖。ggplot 本身就是一个大问题 (2认同)