Legend disappears when specifying a specific color

I’m creating a scatterplot and specifying color using a separate geom_point layer. If I don’t specify color, GGPLOT will give me a legend.


mtcars_new <- mtcars %>% mutate(cyl_label = if_else(cyl > 6, "High CYL", ""),
                  carb_label = if_else(carb > 6, "High CARB", ""))

p <-  mtcars_new %>%
  ggplot(aes(x = hp, y = mpg)) + 
  geom_point(size = 3, color = "green4") 

p + geom_point(mtcars_new %>% filter(cyl_label == "High CYL"), 
             mapping = aes(color = cyl_label), size = 3)

Image with default color

However, if I supply a specific color, GGPLOT does not give me the legend.

p + geom_point(mtcars_new %>% filter(cyl_label == "High CYL"), 
             mapping = aes(color = cyl_label), size = 3, color = "grey50")

Plot with specifying a specific color

Why does this happen and what can I do to address it?

>Solution :

By setting the color additionally as an argument you are overriding the color aesthetic, i.e. it gets "dropped" and you don’t get a legend. Instead I would suggest to simply map on the color aesthetic and use scale_color_manual to set your desired colors.

library(dplyr)
library(ggplot2)

mtcars_new <- mtcars %>% mutate(
  cyl_label = if_else(cyl > 6, "High CYL", ""),
  carb_label = if_else(carb > 6, "High CARB", "")
)

mtcars_new %>%
  ggplot(aes(x = hp, y = mpg)) +
  geom_point(aes(color = cyl_label), size = 3) +
  scale_color_manual(
    values = c("High CYL" = "red", "green4"),
    breaks = "High CYL"
  )

Leave a Reply