geom_text(data = labels, aes(x, y, label = country), size = 5)中aes(x,y)的作用是什么?

What's the function of aes(x,y) in geom_text(data = labels, aes(x, y, label = country), size = 5)?

在我的 EdX 课程的一个例子中,我想知道为什么我们不能只把 label 放在 ggplot(mapping = aes(...)) 中,而是把 aes(x, y) 放在 geom_text 中。那有什么作用?当它只是说 aes(x, y, label = country) 时是否指定 space 来放置标签?

预期寿命时间序列 - 按国家/地区着色并标记的线条,无图例

labels <- data.frame(country = countries, x = c(1975, 1965), y = c(60, 72))
gapminder %>% filter(country %in% countries) %>%
ggplot(aes(year, life_expectancy, col = country)) +
   geom_line() +
   geom_text(data = labels, aes(x, y, label = country), size = 5) +
   theme(legend.position = "none")

简短的回答是您可以将 label 放在原来的 aes(...) 参数中。

aes 是情节美学的论据,包括 yx、一般 size 等任何内容,并传播到任何进一步ggplotgeom_...stat_... 调用。因此,如果您在 aes 参数中添加 label,它将用作对该特定图的任何函数调用中的值, 除非 您设置 inherit.aes = FALSE 此时它将需要一个新指定的 aes(...) 参数。

因此,下面两个我使用 mtcars 数据集的示例是等效的。

data(mtcars)
library(ggplot2)

#Example 1:
ggplot(data = mtcars, aes(x = hp, y = mpg)) + 
    geom_smooth() + 
    geom_text(aes(label = cyl), size = 5)

#Example 2:
ggplot(data = mtcars, aes(x = hp, y = mpg, label = cyl)) + 
    geom_smooth() + 
    geom_text(size = 5)