How to plot several boxplots by group in r? -


id <- 1:10  group <- c(1,1,1,2,2,2,3,3,3,3) var1 <- c(6:15)  var2 <- c(7:16)  var3 <- c(6:11, na, na, na, na) var4 <- c(4:9, na, na, na, na)  data <- data.frame(id, group, var1, var2, var3, var4)  library(dplyr)  data %>% group_by(group) %>% boxplot(var1, var2) 

the last line not work wish. idea 4 boxplots in 1 graphic. 2 each variable. maybe need use ggplot2?

you need reorganize data if want both variables in same plot. here ggplot2 solution:

# load library   library(ggplot2)   library(tidyr)   library(ggthemes)   # reorganize data   df <- gather(data, "id","group")   #rename columns    colnames(df) <- c("id","group","var","value")  # plot   ggplot(data=df) +      geom_boxplot( aes(x=factor(group), y=value, fill=factor(var)), position=position_dodge(1)) +     scale_x_discrete(breaks=c(1, 2, 3), labels=c("a", "b", "c")) +     theme_minimal() +     scale_fill_grey()  

enter image description here

making boxplots same width whole different question (solution here), 1 simple alternative this:

# recode column `group` in `data.frame`.   df <- transform(df, group = ifelse(group==1, 'a', ifelse(group==2, 'b', "c")))  # plot   ggplot(data=df) +    geom_boxplot( aes(x=factor(var), y=value, fill=factor((var))), position=position_dodge(1)) +   geom_jitter(aes(x=factor(var), y=value, color=factor((var)))) +   facet_grid(.~group, scales = "free_x") +   theme_minimal()+   scale_fill_grey() +   theme(axis.text.x=element_blank(),         axis.title.x=element_blank(),         axis.ticks=element_blank()) 

enter image description here


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -