rkm19
rkm19

Reputation: 149

Flat lines in ggplot2 boxplot()

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!

Upvotes: 0

Views: 618

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

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'))

Upvotes: 0

Related Questions