Colouring a particular class

Viewed 109
library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point()

If I want to colour a particular class, let us say 2 seater, what is the modification in the code

2 Answers

Try this. You can wrap the logical condition directly inside colour element:

library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = (class=='2seater'))) + 
  geom_point()+
  labs(color='class')+
  scale_color_discrete(labels=c('TRUE'='2seater','FALSE'='other'))

Output:

enter image description here

As legend will not have a fashion title, you can use labs() to change that or follow the pretty smart advice from @r2evans creating a new column to store the results of the logical condition using dplyr:

library(dplyr)
#Code
mpg %>%
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>%
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point()

Output:

enter image description here

Update:

#Code2
mpg %>% mutate(Color=ifelse(class=='2seater','2seater','Other')) %>%
  ggplot(aes(displ, hwy, colour = Color)) +
  geom_point()+
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))+
  geom_smooth(method = 'lm',aes(group=1),show.legend = F)

Output:

enter image description here

You can try adding specific colors this way too:

ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point() +
scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))
Related