barplot in loop in R

大兔子大兔子 提交于 2019-12-03 17:11:29

If you wrap it in a function like this, you should be able to get it to work and be called multiple times.

colbarplot <- function(group) {

    myd1 <- myd[myd$group == group,]
    filld1 <- filld[filld$group1 == group,]
    blues <- colorRampPalette(c("yellow", "blue"))
    barplot(as.matrix(diff(myd1$avar)), horiz=T,
            col=blues(10)[10* filld1$fillcol], 
            axes=F, xlab="Mark")
    axis(1, labels=myd$label, at=myd$avar)
    axis(3, labels=myd$avar, at=myd$avar)
}

par(mfrow = c(3, 1))
par(mar = c(2.5, 1, 2.5, 1))
sapply(unique(myd$group),function(x) colbarplot(x))

This will give the multiple plots on one page you are after.

Two problems here. You're unintentionally overwriting 'myd' and 'filld' in the loop. Second, you should specify the mfrow at the start, then produce the plots (3 in this example). You're resetting mfrow in the middle. Not what you want.

Try this:

opar <- par(mfrow = c(length(unique(myd$group)), 1), mar = c(2.5, 1, 2.5, 1))

for (i in 1:length(unique(myd$group))){
    myd1 <- myd[myd$group ==i,]
    filld1 <- filld[filld$group1 ==i,]
    blues <- colorRampPalette(c("yellow", "blue"))
    barplot(as.matrix(diff(myd1$avar)), horiz=T, 
       col=blues(10)[10* filld1$fillcol], axes=F, xlab="Mark")
    axis(1, labels=myd1$label, at=myd1$avar)
    axis(3, labels=myd1$avar, at=myd1$avar)
 }

 par(opar);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!