Aesthetic mappings describe how variables in the data are mapped to visual
properties (aesthetics) of geoms. aes
uses non-standard
evaluation to capture the variable names. aes_
and aes_string
require you to explicitly quote the inputs either with ""
for
aes_string()
, or with quote
or ~
for aes_()
.
(aes_q
is an alias to aes_
)
Details
It's better to use aes_q()
, because there's no easy way to create the
equivalent to aes(colour = "my colour")
or aes{x = `X$1`}
with aes_string()
.
aes_string
and aes_
are particularly useful when writing
functions that create plots because you can use strings or quoted
names/calls to define the aesthetic mappings, rather than having to use
substitute
to generate a call to aes()
.
Examples
# Three ways of generating the same aesthetics
aes(mpg, wt, col = cyl)
#> * x -> mpg
#> * y -> wt
#> * colour -> cyl
aes_(quote(mpg), quote(wt), col = quote(cyl))
#> * colour -> cyl
#> * x -> mpg
#> * y -> wt
aes_(~mpg, ~wt, col = ~cyl)
#> * colour -> cyl
#> * x -> mpg
#> * y -> wt
aes_string("mpg", "wt", col = "cyl")
#> * colour -> cyl
#> * x -> mpg
#> * y -> wt
# You can't easily mimic these calls with aes_string
aes(`$100`, colour = "smooth")
#> * x -> `$100`
#> * colour -> "smooth"
aes_(~ `$100`, colour = "smooth")
#> * colour -> "smooth"
#> * x -> `$100`
# Ok, you can, but it requires a _lot_ of quotes
aes_string("`$100`", colour = '"smooth"')
#> * colour -> "smooth"
#> * x -> `$100`
# Convert strings to names with as.name
var <- "cyl"
aes(col = x)
#> * colour -> x
aes_(col = as.name(var))
#> * colour -> cyl