Change colours of particular bars in a bar chart

George Burrows picture George Burrows · Oct 28, 2012 · Viewed 55.3k times · Source

I've been creating some bar-charts and I was wondering is it possible to colour bars on a chart depending on whether they lie above or below the x-axis?

For clarification, this is the type of bar-chart I mean:

enter image description here

Ideally I would like to be able to colour the bars above a separate colour to those below so the graph looks more appealing, I've been searching but I can't find any method of doing this, can anyone help?

Thanks in advance. :)

Answer

Josh O'Brien picture Josh O'Brien · Oct 28, 2012

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" 

enter image description here