0

I have a simple data.frame and here is my script, where I have one color for each Genotype and just wanted to label the 'X' Genotype:

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

However, my legend disappeared and I don't get why. I am interested in Genotype legend.

Picasa
  • 59
  • 1
  • 6
  • linked from following question when I google your exact question https://stackoverflow.com/questions/48768567/reasons-that-ggplot2-legend-does-not-appear – tjebo Feb 14 '21 at 11:05

1 Answers1

1

You need to provide the color= argument inside the aes, to get a legend, and to get the colour you like assigned to factos, provide it using 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)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72