2014-11-03 92 views
1

我的挑战是一次绘制几个条形图,即不同子集的每个变量的绘图。我的目标是比较每个变量的区域差异。我想通过R Markdown将所有生成的图表打印到html文件中。绘制循环中的几个分组条形图[R]

我在制作自动分组条形图时遇到的主要困难是,您需要使用table(data$Var[i], data$Region)制表组,但我不知道如何自动执行此操作。我将非常感谢这方面的提示。

这里是什么我的子集的一个看起来像一个例子:使用beside = TRUE

# To Create this example of data: 
b <- rep(matrix(c(1,2,3,2,1,3,1,1,1,1)), times=10) 
data <- matrix(b, ncol=10) 
colnames(data) <- paste("Var", 1:10, sep = "") 
data <- as.data.frame(data) 
reg_name <- c("North", "South") 
Region <- rep(reg_name, 5) 
data <- cbind(data,Region) 

,我能创造一个分组条形图(按区域VAR1从数据分组):

tb <- table(data$Var1,data$Region) 
barplot(tb, main="Var1", xlab="Values", legend=rownames(tb), beside=TRUE, 
     col=c("green", "darkblue", "red")) 

我想循环这个过程以产生用于实施例10个重复对VAR1到Var10:

for(i in 1:10){ 
    tb <- table(data[i], data$Region) 
    barplot(tb, main = i, xlab = "Values", legend = rownames(tb), beside = TRUE, 
      col=c("green", "darkblue", "red")) 
    } 

[R喜欢apply家庭的功能,因此我试图创建一个功能应用:

fct <- function(i) { 
     tb <- table(data[i], data$Region) 
     barplot(tb, main=i, xlab="Values", legend = rownames(tb), beside = TRUE, 
      col=c("green", "darkblue", "red")) 
     } 
sapply(data, fct) 

我曾尝试其他方法,但我从来没有成功。也许latticeggplot2将提供更简单的方法来做到这一点。我刚刚开始在R,我会很乐意接受任何提示和建议。谢谢!

(我在Windows上运行,与最近Rv3.1.2“Pumpking头盔”)

回答

2

既然你说:“我的目标是比较每个变量的地区差异”,我不知道你”已经选择了最佳的绘图策略。但是,是的,有可能做你在问什么。

这里的默认打印您与您的代码获得以上,以供参考:

enter image description here

如果你想与10个地块为每个变量的列表,你可以做以下(含ggplot)

many_plots <- 

    # for each column name in dat (except the last one)... 
    lapply(names(dat)[-ncol(dat)], function(x) { 

    this_dat <- dat[, c(x, 'Region')] 
    names(this_dat)[1] <- 'Var' 

    ggplot(this_dat, aes(x=Var, fill=factor(Var))) + 
     geom_bar(binwidth=1) + facet_grid(~Region) + 
     theme_classic() 
    }) 

示例输出,用于many_plots[[1]]

enter image description here

如果你想在一个图像中的所有情节,你可以这样做(使用重塑和data.table)

library(data.table) 
library(reshape2) 
dat2 <- 
    data.table(melt(dat, id.var='Region'))[, .N, by=list(value, variable, Region)] 

ggplot(dat2, aes(y=N, x=value, fill=factor(value))) + 
    geom_bar(stat='identity') + facet_grid(variable~Region) + 
    theme_classic() 

enter image description here

...但是这不是一个很大的阴谋。

+0

谢谢Arvi的建议。我更喜欢“许多情节”选项,但是我忽略了变量的名称或数量(VarX)。我尝试过title = paste(名字[i])。 – 2014-11-04 22:30:10

+0

除了这个问题:看来我的地区有非常不同的数字。绘制等于每个值的区域百分比会更好。我正在尝试使用'prop.table'... – 2014-11-04 22:35:56

+0

1)由于上面的代码在var名称上使用'lapply',所以您可以使用'ggtitle(x)'2)修改'this_dat'来显示比例,然后使用'geom_bar(stat ='identity')进行绘图' – arvi1000 2014-11-04 22:39:36