3

I need to create a stacked barplot from data of the form c² = a² + b². a² and b² are normalized by c² such that a and b add up to 1. The data I have requires specific formats so that a and b need to be lists. Below is a simplest reproducible example given those specific formats:

A = list(-2,-1,1,2)
B = list(1,2,3,4)
numA = as.numeric(A)
numB = as.numeric(B)
C = numA*numA + numB*numB
data = matrix(c(numA*numA/C,numB*numB/C),byrow=TRUE,ncol=4)
barplot(data,col=c('black','grey'))

However, when the numA is negative I would like the color to be black, but when numA is positive I would like it to be red. I have created the vector for the colors with the following code

my_cols = c()
for (i in seq_along(A)) {
   if (A[[i]] < 0) {
       color = 'red'
   } else {
       color = 'black'}
   my_cols <- append(my_cols,c(color,'grey'))
}

but trying

 barplot(data,col=my_cols)

simply takes the first two colours and assigns them to all the bars. Is there a way to do what I need in R?

SnowFrog
  • 1,162
  • 4
  • 19
  • 38
  • 2
    your barplot is using one color per row. since you only have two rows, you get two colors. you could split the first row into two depending on the sign of `numA` (i.e., the first row corresponds to red and if numA is negative, then put values in this row; row two is for numA positive, black, and row 3 is all values of numB) and then color, to get something like `data <- matrix(c(.8,0,.2,.2,0,.8,0,.1,.9,0,.2,.8), ncol = 4); barplot(data,col=c('red','black','gray'))` – rawr Jun 11 '14 at 17:14
  • @rawr You suggestion worked. If you turn it into an answer I can accept it. – SnowFrog Jun 12 '14 at 10:00

0 Answers0