Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way of mixing boxplots for different subgroups from the same dataset?

I have this dataframe

A <- c(100,101,102,98,97,93,96)
B <- c("John","Anne","John", "Anne","John","Anne","John")
C <- c("cheap", "cheap", "expensive", "cheap", "expensive", "cheap", "expensive")
D <- c("USA", "Mexico", "Mexico","USA", "Mexico","USA", "Mexico")

dataframe <- data.frame(A, B, C, D)

   A    B         C      D
1 100 John     cheap    USA
2 101 Anne     cheap Mexico
3 102 John expensive Mexico
4  98 Anne     cheap    USA
5  97 John expensive Mexico
6  93 Anne     cheap    USA
7  96 John expensive Mexico

Imagine that I want to create on the same plot, different boxplots, grouping B, C and D columns.

So a total of 6 boxplots (John, Anne, cheap, expensive, USA and Mexico).
Taking into account the the group A values, of course.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem here is that each subgroup have a different total of samples to plot, which makes me very confused.

>Solution :

This problem is a matter of reshaping the data to long format. Then it becomes a standard boxplot.

library(ggplot2)
library(magrittr)
library(tidyr)

dataframe %>%
  pivot_longer(-A) %>%
  ggplot(aes(value, A)) +
  geom_boxplot()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading