Home > database >  Allowing for different colors for boxplot and overlying points in ggplot2
Allowing for different colors for boxplot and overlying points in ggplot2

Time:10-26

Here is the data:

set.seed(1234)
df = tribble(
    ~group,~value,
    "a",   rnorm(1000, mean = 5),
    "b",   rnorm(1000, mean = 7, sd = 1.5),
    "c",   rnorm(1000, mean = 8),
    "c",   rnorm(1000, mean = 9),
    "c",   rnorm(1000, mean = 7)
) %>%
    unnest(value)

I use the code below to create box plot and overlying dots:

library(ggplot2)
ggplot(df, aes(x = group, y = value))  
geom_boxplot(aes(color = group), fill = NA, outlier.shape = NA) 
geom_point(aes(color = group), shape = 21, position = position_jitter(
    seed = 1, width = .05
), alpha = 0.1)

Here is the figure: enter image description here

The border color of the overlying points and the border color of the boxes are identical. For example, when the boxplot is orange, the border of points is also orange. I wish to know how could I allow for different colors for the boxplot and overlying points' border. For example, I wish to make colors of the boxplot to be black, blue, brown for groups a, b, and c, respectively. I also want the color of the border of overlying points to be red, green, yellow.

CodePudding user response:

Maybe you look for something like this:

Transform group to factor and then recode with recode_factor from dplyr package with colors you desire. Then within ggplot assign your new colors:

library(tidyverse)

df %>% 
  mutate(group = factor(group),
         color_group = recode_factor(group, "a"="gold", "b"="purple", "c"="black")) %>% 
  ggplot(aes(x = group, y = value))  
  geom_boxplot(aes(color = color_group), fill = NA, outlier.shape = NA) 
  geom_point(aes(color = group), shape = 21, position = position_jitter(
    seed = 1, width = .05
  ), alpha = 0.1)

enter image description here

CodePudding user response:

Another option to achieve your desired result would be to use the ggnewscale package which allows for multiple scales and legends for the same aesthetic:

library(ggplot2)
library(ggnewscale)

ggplot(df, aes(x = group, y = value))  
  geom_boxplot(aes(color = group), fill = NA, outlier.shape = NA)  
  scale_color_manual(values = c("black", "blue", "brown"))  
  new_scale_color()  
  geom_point(aes(color = group),
    shape = 21,
    position = position_jitter(seed = 1, width = .05), alpha = 0.1
  )  
  scale_color_manual(values = c("red", "green", "yellow"))

  • Related