求助:为NMDS排序图添加stat_ellipse分组填充椭圆
解决NMDS图按分组生成对应配色填充椭圆的问题
问题核心是未给stat_ellipse指定分组美学映射,且未将填充/颜色与分组变量关联,导致椭圆统一颜色且包围所有点。以下是修正方案:
关键修改点
- 给
stat_ellipse添加aes(fill = factor(site), colour = factor(site)),让椭圆按site分组生成 - 使用
geom = "polygon"参数生成填充椭圆,搭配alpha设置透明度避免遮挡散点 - 将
stat_ellipse放在geom_point之前,确保散点显示在椭圆上方
完整修正代码
nmds.data_scores %>% ggplot( aes(x=NMDS1, y=NMDS2)) + # 先绘制填充椭圆(置于散点下方) stat_ellipse(aes(fill = factor(site), colour = factor(site)), geom = "polygon", alpha = 0.2, level = 0.95) + geom_point(aes(colour = factor(site), shape = factor(Group)), size = 3, alpha=0.7) + geom_text(data = nmds.species_scores, aes(x = NMDS1, y = NMDS2, label = species), alpha = 0) + geom_text(aes(label = site, colour = factor(site)), vjust = 1.7, show.legend = FALSE) + labs( title = "Ordination Plot(Years)", colour = "Year Communities", shape = "Temp. Grouping", fill = "Year Communities") + scale_colour_manual(values = years_colors, guide = "none") + scale_fill_manual(values = years_colors, guide = "none") + # 同步填充色与散点配色 scale_shape_manual(values = years_only$point_shape, name = "Temp. Grouping") + coord_equal() + theme_classic()+ theme( panel.background = element_rect(fill = NA, colour = "black", size = 1, linetype = "solid"), legend.position = c(0.10, 0.10), legend.justification = c(0, 0), legend.text = element_text(size = 12), legend.title = element_text(size = 10, face = "bold"), legend.key = element_blank(), legend.box.background = element_rect(color = "black"), ) + theme( axis.text = element_text(size = 10), axis.title = element_text(size=12,color="grey14",face="bold")) + theme(plot.title = element_text(color = "#45ADA8", size=15,face="bold",hjust=0.5)) + geom_hline(yintercept = 0, linetype = "dashed", color = "grey") + geom_vline(xintercept = 0, linetype = "dashed", color = "grey")+ annotate("text", x = -1, y = 0.45, label = paste0("stress: ", format(nmds$stress, digits = 4)), hjust = 0)
补充说明
level = 0.95是默认置信水平,可根据需求调整(如改为0.90)- 若需要显示填充/颜色图例,可删除
scale_colour_manual和scale_fill_manual中的guide = "none"参数 - 调整
alpha值可改变椭圆填充的透明度,数值越小越透明
内容的提问来源于stack exchange,提问作者user390865
相关产品推荐
相关产品推荐

