13.3 Aesthetic mappings
The aesthetics: aes()
allows for some omissions, under certain conditions.
The complete syntax would be:
ggplot( data = ..., mapping = aes(x = ..., y = ..., ...))
In general x =
and y =
inside the aes(x = ..., y = ..., ...)
can be omitted.
Sometimes R asks you about the missing mapping, and this is when more than one layer with different datasets is used. To solve the issue would be enough to add all the specifications inside the aesthetics.
One more interesting thing to mention is:
What manipulation happens when complex tranformations are set inside the aes()?
As an example , if we apply the log transformation:
(the example is from the diamond
dataset)
aes(log(carat), log(price))
What happens behind the scenes is an explicit call to dplyr::mutate()
(The symbol $
is not allowed inside the aes()
)
13.3.1 Specifying the aesthetics in the plot vs. in the layers
All of these alternatives are allowed:
ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class))
ggplot(mpg, aes(displ)) +
geom_point(aes(y = hwy, colour = class))
ggplot(mpg) +
geom_point(aes(displ, hwy, colour = class))
But under some conditions, such as the use of a geom_smooth()
, the position of secondary arguments need to be specified in the layer parameters, as it is important for releasing correct results.
In the first case the smooth line doesn’t show up.
13.3.2 Setting vs. mapping
What is the difference between mapping and setting an aesthetic?
To map an aesthetic to a variable there are different options, you can put the color argument (or other secondary arguments) inside or outside the aesthetic with different results:
geom_...(aes(colour = cut))
geom_...(colour="red")
Or set an aesthetic to a constant, a specific color-value, in case of a color argument:
...,colour = "red")
An alternative would be to use the function:
scale_colour_identity()
In case of more than one geom_smooth()
being used in the plot, the different colors can be specified with scale_color_...()
function.