r - R中循环的条形图

标签 r graphics bar-chart base

这是我的问题:

#data 1:
lab1 <- 1:10
group <- rep(1:3, each = length (lab1))
label <- rep(lab1, 3)
avar <-  rep(c(0, 1, 4, 5, 6, 8, 10,  11, 12,  13), 3)
myd <- data.frame (group, label, avar)

# data 2
fillcol <- rep(rnorm(length(lab1)-1, 0.5, 0.2), 3)
group1 <- rep(1:3, each = length(fillcol)/3)
 # this variable will be used to fill color in bars
 filld <- data.frame(group1, fillcol)

# now plotting
par(mfrow = c(3, 1))
 par(mar = c(2.5, 1, 2.5, 1))

#plot1
myd1 <- myd[myd$group ==1,]
filld1 <- filld[filld$group1 ==1,]
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)

虽然是这个样本数据集,但我有很多变量,我想自动化这个过程。

for (i in 1:length(unique(myd$group))){
         par(mfrow = c(i, 1))
        par(mar = c(2.5, 1, 2.5, 1))
                myd[i] <- myd[myd$group ==i,]
        filld[i] <- filld[filld$group1 ==i,]
      blues <- colorRampPalette(c("yellow", "blue"))
      barplot(as.matrix(diff(myd[i]$avar)), horiz=T, 
   col=blues(10)[10* filld1$fillcol], axes=F, xlab="Mark")
      axis(1, labels=myd[i]$label, at=myd[i]$avar)
        axis(3, labels=myd[i]$avar, at=myd[i]$avar)
        }
 Error in dim(data) <- dim : attempt to set an attribute on NULL
In addition: Warning messages:
1: In `[<-.data.frame`(`*tmp*`, i, value = list(group = c(1L, 1L, 1L,  :
  provided 3 variables to replace 1 variables
2: In `[<-.data.frame`(`*tmp*`, i, value = list(group1 = c(1L, 1L,  :
  provided 2 variables to replace 1 variables

编辑:我想创建一个循环,以便在循环内创建多个图形:

enter image description here

PS:我是 R 和 stackoverflow 的新手。如果问题不合适,请原谅,尽管我阅读了指南并尝试遵守它

最佳答案

如果将它包装在这样的函数中,您应该能够让它工作并被多次调用。

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))

这将在您之后的一页上给出多个图。

关于r - R中循环的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405967/

相关文章:

java - 如何用java制作3D图形?

pandas - 在 pandas barplot 中的每个子组中的条形之间添加空格

r - 从数据表中分离变量并创建新的数据表

r - 如何在 map (ggplot)上放置比例尺和指北针?

c++ - 帮助合并 vector 的算法

javascript - 将水平线添加到我的 chart.js 条形图

excel - 在 Excel 图表标签中使用数学方程

r - R中 "Error: package ' ____ _' was built before 3.0.0: please re-install it"的原因

java - R 无法在 Eclipse 中正确安装...Java 问题?

R 错误 - 范围 0 的表