Home > Net >  How to color geom_boxplot jitter by group
How to color geom_boxplot jitter by group

Time:06-07

I have the following data frame:

plot_dat <- structure(list(Trial = c("Trial1", "Trial1", "Trial1", "Trial2", 
"Trial2", "Trial2", "Trial2", "Trial2", "Trial3", "Trial3", "Trial3", 
"Trial3", "Trial3", "Trial4", "Trial4", "Trial4", "Trial5", "Trial5", 
"Trial5", "Trial5", "Trial6", "Trial6", "Trial6", "Trial6", "Trial6", 
"Trial7", "Trial7", "Trial7", "Trial7", "Trial8", "Trial8", "Trial8", 
"Trial8"), conc = structure(c(4L, 3L, 2L, 5L, 4L, 3L, 2L, 1L, 
5L, 4L, 3L, 2L, 1L, 4L, 3L, 2L, 4L, 3L, 2L, 1L, 5L, 4L, 3L, 2L, 
1L, 5L, 4L, 3L, 2L, 5L, 4L, 3L, 2L), .Label = c("25μg/mL", "50ug/mL", 
"100μg/mL", "200μg/mL", "400μg/mL"), class = "factor"), score = c(108, 
31.9, 15.1, 243, 125, 50.3, 21.3, 12, 200, 130, 73.5, 31.5, 12, 
114, 48.2, 13.8, 130, 70.7, 30.7, 13.6, 260, 117, 47.3, 22.6, 
12, 129, 75.8, 31.3, 11, 244, 92.6, 47, 19.5)), row.names = c(NA, 
-33L), class = c("tbl_df", "tbl", "data.frame"))

It looks like this:

> plot_dat
# A tibble: 33 × 3
   Trial  conc     score
   <chr>  <fct>    <dbl>
 1 Trial1 200μg/mL 108  
 2 Trial1 100μg/mL  31.9
 3 Trial1 50ug/mL   15.1
 4 Trial2 400μg/mL 243  
 5 Trial2 200μg/mL 125  
 6 Trial2 100μg/mL  50.3
 7 Trial2 50ug/mL   21.3
 8 Trial2 25μg/mL   12  
 9 Trial3 400μg/mL 200  
10 Trial3 200μg/mL 130  
# … with 23 more rows

What I want to do is to make a box plot with jitter inside. The jitter point should be colored by Trial columns.

I have this code:

library(tidyverse)

plot_dat %>% 
ggplot( aes(x = conc,  y = score), color = Trial )  
  geom_boxplot(outlier.shape=NA) 
  geom_jitter(width = 0.01, size = 2 )  
  theme_bw()   
  xlab("")   
  ylab("Qubit Read (ng/uL)")

But it failed. It gives this instead:

enter image description here

What's the right way to do it?

CodePudding user response:

You need to use color = Trial inside aes in geom_jitter

Example

library(tidyverse)

plot_dat %>% 
  ggplot(aes(x = conc,  y = score))  
  geom_boxplot(outlier.shape=NA) 
  geom_jitter(aes(color = Trial))  
  theme_bw()   
  xlab("")   
  ylab("Qubit Read (ng/uL)")

enter image description here

  • Related