We may use scale_colour_manual()
and assign custom colours and labels to the various levels of our discrete variable.
Here I use data from iris
as example data and iris$Species
as discrete variable.
library(ggplot2)
# axis labels
xl <- "Sepal Length"; yl <- "Sepal Width"
# custom colours
my_colours <- c('blue4', 'darkorange', '#00b0a6')
my_colours <- setNames(my_colours, unique(iris$Species))
# custom labels
my_labels <- c('species 1', 'species 2', 'species 3')
# median Sepal.Width per Species
medians_SW <- sapply(split(iris, iris$Species), \(x) median(x$Sepal.Width))
# plot
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
geom_point(size = 2, alpha = 0.8) +
geom_hline(aes(yintercept = medians_SW[1]), color = my_colours[1],
linetype = 2, size = 0.8, alpha = 0.8) +
geom_hline(aes(yintercept = medians_SW[2]), color = my_colours[2],
linetype = 2, size = 0.8, alpha = 0.8) +
geom_hline(aes(yintercept = medians_SW[3]), color = my_colours[3],
linetype = 2, size = 0.8, alpha = 0.8) +
xlab(xl) + ylab(yl) + theme_minimal() +
scale_colour_manual(name = 'Species',
breaks = unique(iris$Species),
values = my_colours,
labels = my_labels)
