每个条形定义颜色的条形图

时间:2018-01-17 16:59:22

标签: r plot

我有这个数据(矩阵)

           [,1] [,2] [,3] [,4]
     [1,] 0.02 0.03 0.03 0.05
     [2,] 0.00 0.00 0.04 0.00
     [3,] 0.00 0.00 0.03 0.00
     [4,] 0.00 0.00 0.06 0.00
     [5,] 0.00 0.00 0.07 0.00

我尝试过不同的颜色组合,但不适用。

我希望前两个栏位于blue,第三栏位于这些颜色

colr <- c("red","yellow","green","yellow","red")

blue

中的最后一栏

我甚至尝试过定义颜色矩阵:

colr <- cbind(c("blue","white","white","white","white"),
              c("blue","white","white","white","white"),
              c("red","yellow","green","yellow","red"),
              c("blue","white","white","white","white"),
              c("blue","white","white","white","white"))

barplot(as.matrix(x), col=colr)

请仅使用基本R条形图作为解决方案。谢谢。

2 个答案:

答案 0 :(得分:2)

m = as.matrix(x)
graphics.off()
barplot(m, col = "blue")
barplot(replace(m*0, cbind(1:NROW(m), 3), m[,3]),
        col = c("red","yellow","green","yellow","red"), add = TRUE)

enter image description here

答案 1 :(得分:2)

我需要说这个解决方案不是编程艺术的一部分,但是,它有效。

mm <- matrix(c(0.02, 0.03, 0.03, 0.05, 0.00, 0.00, 0.04, 0.00, 0.00, 0.00, 0.03, 0.00, 0.00, 0.00, 0.06, 0.00,0.00, 0.00, 0.07, 0.00), 5, 4, byrow=T)
my.colors <- list(c("blue"), c("blue"), c("red","yellow","green","yellow","red") , c("blue"))
my.ylim <- c(0, max(colSums(mm)))
my.xlim <- c(0, 5)

for(i in 1:4){
    barplot(matrix(mm[,i]), 
            space=(i-1)*1.5, 
            xlim=my.xlim, ylim=my.ylim, 
            col=my.colors[[i]], add=i!=1)
}

enter image description here