Maximilian
Maximilian

Reputation: 4229

Barplot with defined colour per bar

I have this data (matrix)

           [,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

I have tried different compbinations of colours non of them works.

I would like to have the first 2 bars to be in blue, the third to be in these colours

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

and last column in blue

I have tried even to define matrix of colours:

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)

Please use only base R barplot for solution. Thank you.

Upvotes: 1

Views: 77

Answers (2)

storaged
storaged

Reputation: 1847

I need to say that this solution is not the piece of programming art, however, it works.

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

Upvotes: 2

d.b
d.b

Reputation: 32548

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

Upvotes: 2

Related Questions