【问题标题】:Visualization using boxplot for large datasets使用箱线图对大型数据集进行可视化
【发布时间】:2020-03-31 13:50:20
【问题描述】:

我有一个以下格式的数据框。

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

据此,我需要在商品列中显示每个独特商品的价格分布箱线图。大约有 80 种独特的物品。所以,我不知道如何对它们进行分组,以便我得到至少有 4 个独特项目的箱线图,每个图表的范围和所有 80 个独特项目的多个这样的图表。 我不确定我是否应该重塑我的数据框,即使我需要,它会在什么基础上进行? 我试过使用 facet_wrap 但 nrow 没有任何区别。 对此的任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 为什么不按price 列排序,根据price 列中的一系列值创建一个新列,然后您可以在其中使用facet_wrap()
  • @TheSciGuy 但是,这样相同的项目不会在一起。我需要每个项目的分布对吗?
  • 啊,我假设每个itemprice 都是相似的。如果price 对于相同的items 有很大的不同,那么这样做是没有意义的。

标签: r data-visualization boxplot


【解决方案1】:

您需要根据您的项目名称创建一个分组变量。由于您在示例中的所有项目都称为item#,因此我只是从中提取了数字来创建分组变量:

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

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

【讨论】:

    【解决方案2】:

    如果您希望每个图表有 4 个箱线图,您可以尝试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多