Home > Software design >  match color, line type AND shape in a SINGLE legend ggplot2
match color, line type AND shape in a SINGLE legend ggplot2

Time:11-07

I'm struggling with changing a regression plot

  • the code is:

data %>%
  # filter(!is.na(IND_TEST_SCORE) & !is.na(SCORE)) %>% 
  ggplot(., aes(x = IND_TEST_SCORE, y = SCORE,
                color = TYPE, linetype = TYPE, shape = TYPE))  
  geom_point(alpha = 0.1, color = "red")  
  scale_shape_manual(values = c(16, 17))    ## change shape type
  stat_smooth(formula = y ~ x, method = lm, se = T)  
  scale_linetype_manual(values = c("solid", "dashed"))  
  scale_color_manual(values = c(A = "yellow", B =  "cadetblue2"),
                     label = c(A = "TYPE A", B = "TYPE B"))  
  # scale_linetype(name = "Type:")  
  # facet_grid(~TYPE)  
  labs(x = "IND_TEST_SCORE",
       y = "SCORE",
       title = "Effect of IND_TEST_SCORE and TYPE on SCORE",
       color = "Type:")  
  theme_bw()

Questions:

  • 1 Match colors in scale_color_manual to TYPE
  • 2 Match the legends to the linetype definied in scale_linetype_manual
  • 3 match the legends with shapes and linetype to the one with color
  • 4 get rid of the duplicated legend

ps: I've seen some

PS - you can also color the error bands by adding fill = Type:, setting an alpha level in stat_smooth(), and using your manual color scale for both color and fill by adding aesthetics = c("color", "fill"):

data %>%
  mutate(`Type:` = paste("TYPE", TYPE)) %>%
  ggplot(aes(x = IND_TEST_SCORE, y = SCORE,
                color = `Type:`, fill = `Type:`, linetype = `Type:`, shape = `Type:`))  
  geom_point(alpha = 0.25)  
  scale_shape_manual(values = c(16, 17))    ## change shape type
  stat_smooth(formula = y ~ x, method = lm, se = T, alpha = .15)  
  scale_linetype_manual(values = c("solid", "dashed"))  
  scale_color_manual(values = c("yellow", "cadetblue2"), aesthetics = c("color", "fill"))  
  labs(x = "IND_TEST_SCORE",
       y = "SCORE",
       title = "Effect of IND_TEST_SCORE and TYPE on SCORE")  
  theme_bw()

  • Related