One way is to index a vector of colours with a logical or factor variable (this is a common idiom in R.
set.seed(1)
NAO <- rnorm(40)
cols <- c("red","black")
pos <- NAO >= 0
barplot(NAO, col = cols[pos + 1], border = cols[pos + 1])
The trick here is pos
:
> pos
[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE
[11] TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE TRUE TRUE
[21] TRUE TRUE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE
[31] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
which we coerce to numeric in the barplot()
call:
> pos + 1
[1] 1 2 1 2 2 1 2 2 2 1 2 2 1 1 2 1 1 2 2 2 2 2 2 1 2 1 1 1 1 2
[31] 2 1 2 1 1 1 1 1 2 2
The vector of 1
s and 2
s selects elements from the vector of colour cols
, such that:
> cols[pos + 1]
[1] "red" "black" "red" "black" "black" "red" "black"
[8] "black" "black" "red" "black" "black" "red" "red"
[15] "black" "red" "red" "black" "black" "black" "black"
[22] "black" "black" "red" "black" "red" "red" "red"
[29] "red" "black" "black" "red" "black" "red" "red"
[36] "red" "red" "red" "black" "black"
which is the colour passed on to each bar drawn.
In the code above I also set the border of the bars to the relevant colour, via argument border
.
The resulting plot should look like this
