Basil
Basil

Reputation: 1004

Colour scheme in a separate dataframe

I can specify the colors in a plot by using scale_color_manual as below:

library(tidyverse)
mpg %>% 
filter(class=="2seater"|class=="minivan")%>%
ggplot(aes(displ, hwy,colour=class)) + 
  geom_point()+
  scale_color_manual(values=c(
    "2seater"="green",
    "minivan"="red"))

But if I had a separate dataframe as below:

class<-c("2seater","minivan")
color<-c("green","red")
colorscheme<-data.frame(class,color,stringsAsFactors = FALSE)

How can I use this to specify the colors within the ggplot?

Upvotes: 2

Views: 375

Answers (2)

Duck
Duck

Reputation: 39585

Another option can be scale_color_identity() after joining:

library(tidyverse)
#Code
mpg%>%filter(class=="2seater"|class=="minivan")%>%
  left_join(colorscheme) %>%
  ggplot(aes(displ, hwy,colour=color)) + 
  geom_point()+
  scale_color_identity(guide = "legend",
                       labels=c("2seater","minivan"),name='class')

Output:

enter image description here

Upvotes: 1

M--
M--

Reputation: 28826

mpg %>% 
  filter(class %in% c("2seater", "minivan")) %>%
  ggplot(aes(displ, hwy, color = class)) + 
  geom_point() + 
  scale_color_manual(values = colorscheme$color, 
                     labels = colorscheme$class)

Upvotes: 4

Related Questions