Hello,
I'm writing a function and inside this function I need to generate a plot, using ggplot2. The user has the option to highlight specific points of this plot, e.g the top or bottom 10% and also some specific points (controls).
I'm struggling to add a legend to this plot, since it is conditional to the parameters specified by the users. I would like a legend that specifie: top = green, bottom = red and controls = blue.
Do you have any idea about it?
Please, see a sample of my codes and data bellow.
Thanks in advance.
res <- data.frame(genotype = c("a","c","b","d"), superiority = c(1.35,2.45,5.73,7.14),mean = c(7.33,7.24,7.28,7.54))
plot = TRUE
top = TRUE
bottom =TRUE
controls = "c"
percentage = 10
if(plot == TRUE){
(p <- ggplot(res, aes(x=mean, y=superiority), label = genotype) +
geom_point(colour ="black") )
if(top == TRUE){
p <- p + geom_point(data = head(res, ceiling((percentage*nrow(res))/100)), aes(x=mean, y=superiority),
colour = "green") +
geom_label_repel(data = head(res, ceiling((percentage*nrow(res))/100)),
aes(label = head(res, ceiling((10*nrow(res))/100))$genotype))
}
if(bottom == TRUE){
p <- p + geom_point(data = tail(res, ceiling((percentage*nrow(res))/100)), aes(x=mean, y=superiority),
colour = "red") +
geom_label_repel(data = tail(res, ceiling((percentage*nrow(res))/100)),
aes(label = tail(res, ceiling((10*nrow(res))/100))$genotype))
}
if(!is.null(controls)){
p <- p + geom_point(data = res[res$genotype== controls,],aes(x=mean, y=superiority),
colour = "blue") +
geom_label_repel(data = res[res$genotype== controls,],
aes(label = res$genotype[res$genotype== controls]))
}
p <- p + labs(y = "Superiority")
}
p