Visualization using boxplot for large datasets

Viewed 486

I have a dataframe in the following format.

item    price
item1    23
item2    45
item1    24
item3    98
item2    45.9
item3    97.2

From this, I need to display boxplots of price distribution for every unique item in the item column. There are about 80 unique items. So, I am not sure how to group them such that I get boxplots with atleast 4 unique item's with its range in each graph and multiple such graphs for all the 80 unique items. I am not sure if I should reshape my dataframe and even if I need to , on what basis would it be? I have tried with facet_wrap but the nrow is not making any difference. Any help with this will be much appreciated.

Thanks in advance.

2 Answers

You'll need to make a grouping variable based on your item names. Since all of your items in the example are called item#, I just pulled the number from them to make a grouping var:

df <- df %>%
  mutate(group = gsub("item", "", item))

p <- ggplot(df, aes(x=item, y=price)) + 
  geom_boxplot() +
  facet_wrap(item~group,scales="free")
p

If you want to have 4 boxplots per graph as you wrote you can try:

#library
library(tidyverse)
library(ggplot2)

#simulate your data
set.seed(2323)
data <- tibble(item=rep(paste("item",1:80),sample(1:10,80, replace=T)),
               price=sample(1:10,407,replace=T))


#group you data
n=4 #groups

data %>% 
  mutate(item=factor(item,levels=unique(item))) %>% 
  group_by(item) %>% 
  mutate(nr=group_indices()) %>% 
  mutate(supergroup=as.numeric(cut(nr,seq(0,length(unique(.$nr)),n)))) %>% 
  select(item,price,supergroup) -> grouped_data

#draw plot         
ggplot(grouped_data,aes(x=item,y=price)) +
  geom_boxplot() + 
  facet_wrap(~supergroup,scales="free") +
  theme(axis.text.x = element_text(angle=90, hjust=1))

enter image description here

Related