图例在 geom_label_repel() 后消失

Legend disappeared after geom_label_repel()

我有一个简单的 data.frame,这是我的脚本,其中每种基因型都有一种颜色,只是想标记 'X' 基因型:

ggplot(b, aes(x= V1, y = V2, label = Sample_name)) + 
  geom_point(color = dplyr::case_when(b$Genotype == "X" ~ "#606060", 
                                      b$Genotype == "Y" ~ "#85C1E9",
                                      b$Genotype == "Z" ~ "#2980B9",
             size = 2, alpha = 0.8) +
  geom_label_repel(data = subset(b, Genotype == "X"),
                   box.padding   = 0.35, 
                   point.padding = 0.5,
                   size          = 4,
                   segment.color = 'grey50')

然而,我的传说消失了,我不明白为什么。我对基因型图例感兴趣。

您需要在 aes 中提供 color= 参数以获得图例,并获得您喜欢分配给 factos 的颜色,使用 scale_color_manual 提供它:

library(ggplot2)
library(ggrepel)

b = data.frame(V1 = 1:12 , V2 = 0.5*(1:12)^2,
               Sample_name = paste0("s",1:12),
               Genotype = rep(c("X","Y","Z"),each=4))
               
ggplot(b, aes(x= V1, y = V2, label = Sample_name,col=Genotype)) + 
geom_point(size = 2, alpha = 0.8) +
scale_color_manual(values = c("#606060","#85C1E9","#2980B9"))+
geom_label_repel(data = subset(b, Genotype == "X"),
                   box.padding   = 0.35, 
                   point.padding = 0.5,
                   size          = 4,
                   segment.color = 'grey50',
                   show.legend=FALSE)