In the previous line of code, we define the mapping
aes(population/10^6, total)
twice, once in each geometry. We can avoid
this by using a global aesthetic mapping. We can do this when we
define the blank slate ggplot
object. Remember that the function
ggplot
contains an argument that permits us to define aesthetic
mappings:
args(ggplot)
#> function (data = NULL, mapping = aes(), ..., environment = parent.frame())
#> NULL
If we define a mapping in ggplot
, all the geometries that are added as
layers will default to this mapping. We redefine p
:
p <- murders %>% ggplot(aes(population/10^6, total, label = abb))
and then we can simply write the following code to produce the previous plot:
p + geom_point(size = 3) +
geom_text(nudge_x = 1.5)
We keep the size
and nudge_x
arguments in geom_point
and
geom_text
, respectively, because we want to only increase the size of
points and only nudge the labels. If we put those arguments in aes
then they would apply to both plots. Also note that the geom_point
function does not need a label
argument and therefore ignores that
aesthetic.
If necessary, we can override the global mapping by defining a new mapping within each layer. These local definitions override the global. Here is an example:
p + geom_point(size = 3) +
geom_text(aes(x = 10, y = 800, label = "Hello there!"))
Clearly, the second call to geom_text
does not use population
and
total
.