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?