首页 文章

从大量数据创建包含多列的条形图(在R中)

提问于
浏览
1

我使用大量数据(n = 2057),我的数据框看起来像:

id_num    Gender   Protein_Milk   Protein_Cheese
 1       2345       1           4.5           3.4
 2       45983      2           5.6           5.2
 .         .        .            .             .
 .         .        .            .             .
 .         .        .            .             .
2057    13454       1           2.6            8.5

我想创建一个barplot,在x轴上并排排列Protein_Milk和Protein_Cheese,按性别分组 . Y轴显示蛋白质(g)的平均值 . 问题是,我无法创建条形图,其中包含两列 . 所以每列有2个不同的条形图(Protein_Milk / Protein_Cheese) .

我的R命令:

Data_Frame$Gemder<-factor(Data_Frame$Gender, levels = c(1,2), labels = c("Men", "Women"))
  Barplot<-ggplot(Data_Frame, aes(Gender, Protein_Milk))
  Barplot +
  stat_summary(fun.y = mean, geom = "bar")+
  stat_summary(fun.data = mean_cl_normal, geom = "errorbar")

有人有什么建议吗?提前致谢

编辑:由于我的数据很大,我不能在这里使用解决方案:

Creating grouped bar-plot of multi-column data in R

我需要找到一种方法如何使用两列创建条形图,而不是在c()或read.table(text = " ")中写入所有条目,因为每列2057条目需要很长时间 .

1 回答

  • 0

    仍然不完全确定您想要的输出类型,但这里's an example. The main problem is that you'重新数据是长格式的,需要采用高格式 . 有关更多信息,请查看:http://r4ds.had.co.nz/tidy-data.html .

    这是我的解决方案,它使用构面包装为每个性别并排放置图表 . 为简单起见,我正在制作一些虚拟数据 .

    library(tidyverse) 
    
    data <- tibble(id = c(1:4), 
                   gender = c(1, 2, 1, 2), 
                   protein_cheese = c(4, 5, 6, 7), 
                   protein_milk = c(6, 7, 8, 9)
            )
    
    data %>%
      gather(key = type, 
             value = protein,
             protein_cheese:protein_milk) %>%
             ggplot(aes(x = type, y = protein)) +
             geom_col() +
             facet_wrap( ~ gender)
    

相关问题