在ggplot2中同时绘制个体和平均值:错误“错误:必须由aes()创建映射”

时间:2019-09-05 01:54:35

标签: r ggplot2 plot aes

我正在尝试在同一ggplot上绘制个体和均值。我需要使个体和平均值之间的颜色相同。 Aes似乎是我的问题的根源,我有更多的观察数> 3000,因此查看平均值和个人在情节空间中的位置将非常重要。 我尝试将所有内容都分成data.frames,以解决在es函数中使用“ $”的问题。我认为在es函数中使用“颜色”或“标签”时会出现问题。也许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)

我希望看到平均值与各自的颜色相同。希望这会演变成允许使用标签的相同期望。

1 个答案:

答案 0 :(得分:1)

明确说明数据源和es映射,它应该起作用:

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))

output