Plotting both individuals and average values in ggplot2: error "Error: `mapping` must be created by `aes()`"

Plotting both individuals and average values in ggplot2: error "Error: `mapping` must be created by `aes()`"

我正在尝试在同一个 ggplot 上同时绘制个人和平均值。我需要让个体和平均值之间的颜色相同。 Aes 似乎是我问题的根源,我有更多 > 3000 的观察结果,查看平均值和个体在图中的位置非常重要 space。 我尝试将所有内容分成 data.frames 以解决在 aes 函数中使用“$”的问题。我认为当我在 aes 函数中使用 "color" 或 "label" 时会出现问题。也许,ggplot 不喜欢物种名称的数量不一样?

# Libraries needed for example
library(dplyr)
library(ggplot2)

# Individuals PC1 and PC2 values
pc1 <- c(1,2,3,4,5,6,7,8,9,10)
pc2 <- c(4,5,6,7,8,9,10,11,12,13)
species <- c("D.a", "D.a", "D.b","D.b","D.c","D.c","D.d","D.d", "D.e", 
"D.e")

# Individual data frame
P1 <- cbind.data.frame(species,pc1,pc2)

# Averages of individuals
P2 <- P1 %>% group_by(species) %>%  summarise(pc1 = mean(pc1), pc2 = 
mean(pc2))

# GGplot
ggplot(P1, aes(x= pc1, y= pc2, color= species)) + geom_point(alpha= 0.2) 
+ geom_point(P2)

我希望看到平均值与各自个体的颜色相同。这有望演变成允许对标签有相同的期望。

明确数据源和 aes 映射,它应该可以工作:

ggplot(P1) + 
    geom_point(alpha = 0.2, aes(x = pc1, y = pc2, color = species)) +
    geom_point(data = P2, aes(x = pc1, y = pc2, color = species))