Here's one strategy:
## Create a reproducible example
set.seed(5)
x <- cumsum(rnorm(50))
## Create a vector of colors selected based on whether x is <0 or >0
## (FALSE + 1 -> 1 -> "blue"; TRUE + 1 -> 2 -> "red")
cols <- c("blue", "red")[(x > 0) + 1]
## Pass the colors in to barplot()
barplot(x, col = cols)
If you want more than two value-based colors, you can employ a similar strategy (using findInterval()
in place of the simple logical test):
vals <- -4:4
breaks <- c(-Inf, -2, 2, Inf)
c("blue", "grey", "red")[findInterval(vals, vec=breaks)]
# [1] "blue" "blue" "grey" "grey" "grey" "grey" "red" "red" "red"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…