P. Denelle P. Denelle - 4 months ago 20
R Question

Unique legend for two different aesthetics with ggplot2

A very simple question I guess but I couldn't find any answer on it.

Let's draw an example dataset with 4 columns. I want to plot two different points on the same plot, so with different aesthetics, and have a column legend describing them according their respective colors.

library(ggplot2)

set.seed(10)
ex <- data.frame("a" = c(1:100), "b" = rnorm(100),
"c" = seq(50, 249, 2), "d" = rnorm(100))

plot_ex <- ggplot(ex, aes(a, b)) +
geom_point(colour = "dodgerblue", cex = 2) +
geom_point(aes(x = c, y = d), colour = "firebrick3", cex = 2) +
theme_classic() +
labs(x = "X axis", y = "Y axis")

plot_ex


I tried to add a
scale_color_manual
line, but I probably coded it wrong:

plot_ex +
scale_color_manual(values = c("dodgerblue", "firebrick3"), label = c("first", "second"), name = "")

Answer

I believe ggplot only creates a legend based on what's in the aes. So you can move the colour into the aesthetic of each geom_point and then relabel them in the scale_colour_manual.

plot_ex <- ggplot(ex) +
    geom_point(aes(x = a, y = b,colour = "dodgerblue"),cex = 2) +
    geom_point(aes(x = c, y = d,colour = "firebrick3"), cex = 2) +
    theme_classic() +
    labs(x = "X axis", y = "Y axis") 

plot_ex +
    scale_colour_manual(values = c("dodgerblue", "firebrick3"), label = c("first", "second"), name = "")