如何分别为每个组制作条形图?

时间:2015-10-12 09:41:05

标签: r graph bar-chart

我有500个小组的数据,每个小组都有不同的学生分数。我想为每个组制作单独的条形图(在R中),这样学生应该在x axix上,他们的分数在y轴上。我尝试使用ggplot2,但它为所有500个组生成单个条形图。我的数据采用以下形式:我知道如何为R中的每个组单独创建数据?       enter image description here

2 个答案:

答案 0 :(得分:1)

library(plyr)
library(ggplot2)
dataset <- expand.grid(Group = 1:3, Student = LETTERS[1:3]) 
dataset$Score <- runif(nrow(dataset), max = 100)
dlply(dataset, ~Group, function(x){
  ggplot(x, aes(x = Student, y = Score)) + geom_bar(stat = "identity")
})

答案 1 :(得分:1)

我们可以使用base R。我们通过“群组”列split数据集创建list,循环浏览names元素的list,分别为每个群组创建barplot并将其另存为png文件。

lst <- split(df1[-1], df1$Group)
invisible(lapply(names(lst), function(nm1) {
   png(paste0('barplot_', nm1, '.png'))
   barplot(setNames(lst[[nm1]]$Score, lst[[nm1]]$Student), 
                              main=paste0('barplot of Group', nm1))
   dev.off()
 }))

注意:标题(main=)和文件名可以相应更改。