Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
  )

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading