Home > OS >  Setting colors of boxplot & jitter point in custom manner ggplot2
Setting colors of boxplot & jitter point in custom manner ggplot2

Time:11-09

given the following dataset, how do I go about setting the outline of the boxes to black (or any other colour I want), while customly colouring the jittered points? I know how to do this in a simple boxpot, where dodging due to two subgroups is not necesary, but run into grouping issues if I try to mess with the code shown below.

Line <- c("A", "A", "B", "B")
FC <- c(2, -1, 3, -0.5, 2.1, 0, 2.2, -2, 1.8, -0.1, 2, -1)
TM <- c("control", "exp", "control", "exp", "control", "exp", "control", "exp", "control", "exp", "control", "exp")
df1 <- data.frame(Line, FC, TM)
head(df1)

library(ggplot2)
cbpallette=c("#EF9F26", "#082F6D")
df1 %>%
  ggplot(aes(x=Line,y=FC, color=TM))   
  stat_boxplot(geom = 'errorbar', width=0.15, position = position_dodge(width=0.6))  
  geom_boxplot(outlier.shape=NA, width=0.4, position = position_dodge(width=0.6))  
  geom_point(position=position_jitterdodge(dodge.width = 0.6, jitter.width = 0.1), alpha=0.4)   theme_classic()  
  scale_color_manual(values = cbpallette)  
  scale_y_continuous(limits=c(-3, 3), breaks=c(-3, -2, -1, 0, 1, 2, 3))   theme(axis.ticks.length = unit(-0.1, "cm"))

Example

CodePudding user response:

Remove color from the initial call to ggplot, like this the several layers will not inherit that aesthetic. Then, put it in geom_point.
Also, I have used the new pipe operator introduced in R 4.1.0, in order to avoid loading an extra package.

Line <- c("A", "A", "B", "B")
FC <- c(2, -1, 3, -0.5, 2.1, 0, 2.2, -2, 1.8, -0.1, 2, -1)
TM <- c("control", "exp", "control", "exp", "control", "exp", "control", "exp", "control", "exp", "control", "exp")
df1 <- data.frame(Line, FC, TM)
head(df1)
#>   Line   FC      TM
#> 1    A  2.0 control
#> 2    A -1.0     exp
#> 3    B  3.0 control
#> 4    B -0.5     exp
#> 5    A  2.1 control
#> 6    A  0.0     exp

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2

cbpallette=c("#EF9F26", "#082F6D")

df1 |>
  ggplot(aes(x=Line,y=FC))   
  stat_boxplot(geom = 'errorbar', width=0.15, position = position_dodge(width=0.6))  
  geom_boxplot(outlier.shape=NA, width=0.4, position = position_dodge(width=0.6))  
  geom_point(
    aes(color=TM),
    position=position_jitterdodge(dodge.width = 0.6, jitter.width = 0.1), 
    alpha=0.4)   
  scale_color_manual(values = cbpallette)  
  scale_y_continuous(limits=c(-3, 3), breaks=c(-3, -2, -1, 0, 1, 2, 3))   
  theme_classic()  
  theme(axis.ticks.length = unit(-0.1, "cm"))

Created on 2022-11-09 with Plot

  • Related