0

I am trying to plot some grouped boxplots with ggplot2 and I have been having trouble because the boxplots are just showing up as flat lines.

The data frame is as follows:

   col1 col2 col1.1 col2.1 col1.2 col2.2 group 
a  0.1   ...                              G1
b  0.2   ...                              G1
c  0.3   ....                             G2
d  0.3   ....                             G2
e  0.1   ...                              G3
f  0.1   ...                              G3
g  0.1   ...                              G3

column names : col1 , col1.1, col1.2, col2, col2.1, and col2.2 Row names : a,b,c,d,e,f,g The group column indicates the group to which each row belongs to.

I want to be able to separate out each group , and plot the boxplots for each type of column. ie, I would have converted all col1, col1.1 and col1.2 into 'col1' and plot boxplots for that group , similarly for col2.

My code is as follows:

G1 = df[df$group == "G1",]
G1 = G1[,-7]

p = G1[gtools::mixedsort(rownames(G1)),]
p$name = rownames(p)
p = reshape2::melt(p, id.vars="name")
colnames(p) <-c("name","group","values") 
p$group = gsub("\\..*", "" , p$group)
p$group = factor(p$group, levels = c("col1","col2"))

plt1 = ggplot(p, aes(x = factor(group), y = values, fill = name)) + geom_boxplot() + scale_fill_brewer(palette="Set3")  + xlab("group") + ylab("Values") 

However, I am getting flat lines in my boxplot with this code. Please help me out if you can spot my mistake.

Thanks in advance!

rkm19
  • 149
  • 1
  • 7
  • 1
    [See here](https://stackoverflow.com/q/5963269/5325862) on making a reproducible example that is easier for folks to help with. That isn't enough of a data sample to make meaningful boxplots, and most of your code seems to be prep for plotting—try to give us a sample of the data that's ready to plot, so we're focusing on debugging the plot rather than the steps to reshape the data – camille May 24 '21 at 18:41

1 Answers1

0

You can try this -

library(tidyverse)

df %>%
  pivot_longer(cols = -group, 
               names_to = '.value', 
               names_pattern = '(col\\d+)') %>%
  pivot_longer(cols = -group) %>%
  ggplot(aes(x = factor(group), y = value, fill = name)) + 
  geom_boxplot() + 
  scale_fill_brewer(palette="Set3")  + 
  xlab("group") + ylab("Values") 

enter image description here data

Reproducible data -

set.seed(123)
df <- data.frame(col1 = rnorm(7), col2 = runif(7), col1.1 = rnorm(7), 
                 col2.1 = rnorm(7), col1.2 = runif(7), col2.2 = rnorm(7), 
                 group = c('G1', 'G1', 'G2', 'G2', 'G3', 'G3', 'G3'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213