R:循环为每个因子水平创建一个单独的条形图

R: loop to create a separate barplot for each factor level

我学会了如何安排多个地块:

windows(width=18,height=3) 
par(las=1,cex.lab=0.75,cex.axis=0.6, bty="n", mgp = c(1, 0.6, 0),oma = c(2,4,2,0) + 0.1, mar = c(4,0,3,3) + 0.1)
a=layout(matrix(c(1,2,3,4), nrow = 1, ncol = 4,byrow=T))
layout.show(a) 

而且我知道如何创建一个使用部分数据(因子水平之一)的图:

xmin=0
xmax=250
ymin=0
ymax=70
with(subset(df, Frequency=='6000'), barplot(value, beside=TRUE, col='black', ylim=c(ymin,ymax),xlim=c(xmin,xmax)))
rect(25,0,55,60, col= rgb(119,136,153, alpha=70, maxColorValue=225), border = "transparent")
axis(1, at=seq(0,250, by=50))

我正在尝试学习如何有效地为不同的因子(频率)水平添加相同的图。我知道我可以 select 一个不同的子集,但这对于许多因子水平来说效率很低。

我尝试过类似的方法,但它似乎不起作用:

for ( i in 1:length(unique(df$Frequency)) ){
value <- subset( df, Frequency == unique ( df$Frequency )[i] )
barplot(value, main = paste0("Frequency: ",  unique(df$Frequency)) )
}

这是我的第一个循环,所以任何解释都会非常有帮助...

我的数据: https://www.dropbox.com/s/tie9rrnmdxuua8c/df.csv?dl=0

df$Frequency = as.factor(df$Frequency)

有人帮我解答了这个问题。解决方案如下。

# space for plots

windows(width=18,height=3) 
par(las=1,cex.lab=0.75,cex.axis=0.6, bty="n", mgp = c(1, 0.6, 0),oma = c(2,4,2,0) + 
0.1, mar = c(4,0,3,3) + 0.1)
a=layout(matrix(c(1,2,3,4), nrow = 1, ncol = 4,byrow=T))
layout.show(a)

# axes' limits

xmin=0
xmax=250
ymin=0
ymax=70

# loop

for ( i in 1:length(unique(df$Frequency)) ){

 value <- subset( df, Frequency == unique ( df$Frequency )[i] )

barplot(value$value, main = paste0("Frequency: ",  unique(df$Frequency)[i]),ylim=c(ymin,ymax),xlim=c(xmin,xmax) )
rect(25,0,75,70, col= rgb(119,136,153, alpha=70, maxColorValue=225), border = "transparent")
axis(1, at=seq(0,300, by=50))

}