littleworth
littleworth

Reputation: 5169

How to color jitter by category in ggboxplot

I have the following data frame:

library(tidyverse)
dat <- structure(list(feat = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "KyteDoo", "FoldIndex"
), class = "factor"), dose = c("0.3mM", "1mM", "3mM", "10mM", 
"20mM", "0.3mM", "1mM", "3mM", "10mM", "20mM", "0.3mM", "1mM", 
"3mM", "10mM", "20mM"), vimp = c(-0.0025, 0, 0.0328571428571429, 
0.025, 0.0425, 0.005, 0.015, 0.0228571428571429, 0.0175, 0.02, 
0.0125, 0.01, 0.02, 0.0325, 0.015)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -15L))

It looks like this:

> dat
# A tibble: 15 × 3
   feat      dose     vimp
   <fct>     <chr>   <dbl>
 1 A         0.3mM -0.0025
 2 A         1mM    0     
 3 A         3mM    0.0329
 4 A         10mM   0.025 
 5 A         20mM   0.0425
 6 KyteDoo   0.3mM  0.005 
 7 KyteDoo   1mM    0.015 
 8 KyteDoo   3mM    0.0229
 9 KyteDoo   10mM   0.0175
10 KyteDoo   20mM   0.02  
11 FoldIndex 0.3mM  0.0125
12 FoldIndex 1mM    0.01  
13 FoldIndex 3mM    0.02  
14 FoldIndex 10mM   0.0325
15 FoldIndex 20mM   0.015 

And with this code:

 library(ggpubr)
 p <- ggboxplot(dat, x = "feat", y = "vimp",  add = "jitter") + 
 theme(axis.text.x=element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12))  + 
 xlab("") + 
 ylab("Variable Importance")

I can get this plot:

enter image description here

What I want to do is to color each dot in the jitter based on dose category. I tried this but failed

 ggboxplot(dat, x = "feat", y = "vimp",  add = "jitter", color = "dose")

enter image description here

What's the right way to do it?

Upvotes: 0

Views: 2858

Answers (1)

stefan
stefan

Reputation: 125268

One option to achieve your desired result would be to add the jittered points via a geom_jitter layer:


library(ggpubr)
#> Loading required package: ggplot2
library(ggplot2)

ggboxplot(dat, x = "feat", y = "vimp") +
  geom_jitter(aes(color = dose)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
  xlab("") +
  ylab("Variable Importance")

Upvotes: 1

Related Questions