Combining legends made by scale_shape_manual with a named vector

Viewed 366

I want to use colour and shape aesthetics in a ggplot to both represent the same variable. I am using scale_shape_manual because I don't like the default shapes. To make sure I assign the desired shape to each value, I am giving values a named vector. The plot is fine, but I have two legends, one for colour, one for shape. I presume this is because shape has a named vector but colour has an unnamed vector.

I want there to be a single combined colour/shape legend, as there would have been had I used an unnamed vector. Any suggestions?

I could use scale_colour_manual with a named vector, but want to use something like scale_colour_brewer. Using labs to give colour and species the same name does not help (they already have the same name).

library(ggplot2)
data(penguins, package = "palmerpenguins")

ggplot(penguins, 
       aes(x = body_mass_g, y = bill_length_mm, colour = species, shape = species)) +
  geom_point() +
  scale_shape_manual(values = c(Adelie = 17, Gentoo = 16, Chinstrap = 6))

Created on 2021-08-28 by the reprex package (v2.0.1)

2 Answers

You could add scale_color_manual(values = c(Adelie = "red", Gentoo = "green", Chinstrap = "blue")) to override the existing color:

The advantage is: you can individually define the colors:

library(ggplot2)
data(penguins, package = "palmerpenguins")

ggplot(penguins, 
       aes(x = body_mass_g, y = bill_length_mm, colour = species, shape = species)) +
    geom_point() +
    scale_shape_manual(values = c(Adelie = 17, Gentoo = 16, Chinstrap = 6)) +
    scale_color_manual(values = c(Adelie = "red", Gentoo = "green", Chinstrap = "blue"))

enter image description here

Did you expect such an effect?

library(ggplot2)
data(penguins, package = "palmerpenguins")


ggplot(penguins, 
       aes(x = body_mass_g, y = bill_length_mm, colour = species, shape = species)) +
  geom_point() +
  scale_shape_manual(values = c(17, 6, 16))

enter image description here

Related