Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

r - Change colours of particular bars in a bar chart

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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...