0

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 = "")
P. Denelle
  • 790
  • 10
  • 24

1 Answers1

0

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 = "")
  • This works indeed, I wonder if they is other way to proceed though. Thanks. – P. Denelle Aug 02 '16 at 18:35
  • This is bad practice. Good practice is to melt your data into long format and use a single `geom_point` call (an example can be found at aosmith's suggested duplicated). – Gregor Thomas Aug 02 '16 at 18:37
  • Note that inside `aes`, the `colour = ` will be interpreted as a data value, not an explicit color. You could just as well replace `colour = "dodgerblue"` with `colour = 'first'` or `colour = 'blah'`. – Gregor Thomas Aug 02 '16 at 18:39