Home > front end >  Color geom_boxplots based on a specific column in a R dataframe
Color geom_boxplots based on a specific column in a R dataframe

Time:08-20

I am using the following code to generate boxplots. I want to color the boxes based on a column name in some data frame df which has 3 columns diff, grp, and class. The example below attempts to color boxes based on class but does not produce desired results. It should produce 6 boxplots: 2 for each group in 2 different colors based on class column but it produces only 3 plots as shown below

enter image description here

Any suggestions will be highly appreciated. Sample code and data for testing is as follows,

df <- readxl::read_xlsx("~/Downloads/df_new_boxplot2.xlsx", sheet = 2, col_names = TRUE)
p1 <- ggplot2::ggplot(df, aes(x = grp, y = diff, group = grp))  
  geom_boxplot(aes(fill = class))  
  xlab("")  
  ylab("diff")  
  theme(
    axis.title = element_text(size = 9),
    axis.text.x = element_text(size = 9),
    axis.text.y = element_text(size = 9)
  )

print(p1)



    diff            grp     class
    0.184258888     G1      ess
    0.19497884      G1      ess
    0.228319959     G1      ess
    -0.029457054    G1      non
    0.167004668     G1      non
    0.133294883     G1      non
    -0.350721613    G1      non
    -0.020916168    G2      non
    0.061094133     G2      non
    0.223643098     G2      non
    0.18530414      G2      non
    -0.091747545    G2      non
    -0.183416747    G2      ess
    -0.123086067    G2      ess
    -0.193987505    G2      ess
    -1.158739554    G2      ess
    -0.002487487    G2      ess
    -0.405122069    G2      ess
    -0.023079965    G2      ess
    0.348647385     G3      non
    0.418440731     G3      non
    0.584033387     G3      non
    0.062912024     G3      non
    0.731170886     G3      non
    0.704519206     G3      non
    0.554128995     G3      ess
    0.401225253     G3      ess
    0.026531873     G3      ess
    0.332660319     G3      ess
    0.014057467     G3      ess
    0.463902969     G3      ess
    0.149713663     G3      ess

CodePudding user response:

You should use interaction(class, grp) in your boxplot like this:

library(ggplot2)
p1 <- ggplot2::ggplot(df, aes(x = grp, y = diff))  
  geom_boxplot(aes(interaction(class, grp), fill = class))  
  xlab("")  
  ylab("diff")  
  theme(
    axis.title = element_text(size = 9),
    axis.text.x = element_text(size = 9),
    axis.text.y = element_text(size = 9)
  )

print(p1)

Created on 2022-08-19 with reprex v2.0.2

  • Related