Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Barchart coloring with a vector in R

Tags:

r

bar-chart

I am attempting to create a simple barplot with both negative and positive values with my input as a vector. I would like the barplot to display the positive values colored in red and the negative values colored in blue. I understand this problem is simple, but I cannot seem to figure it out.

Here is my vector:

x <- (1.9230769,  1.2961538,  0.2576923, -1.5500000, -1.3192308, 
0.2192308,  1.8346154, 1.6038462,  2.5653846,  4.1423077)

I have attempted the code:

barplot(x, ylim=c(-8,8), if(x>0) {col="red"} else {col="blue"})

but I keep getting an error that says

"In if (x > 0) { : the condition has length > 1 and only the first element will be used"

How can I get it to understand to run through the entire vector and plot it conditionally with red and blue?

Thanks,

Adam

like image 556
user3720887 Avatar asked Jun 09 '14 01:06

user3720887


1 Answers

Use

barplot(x, ylim=c(-8,8), col=ifelse(x>0,"red","blue"))

col= expects a vector with the same length as x (or it will recycle values). And you can't really conditionally specify parameters like that. The ifelse will make the vector as desired unlike if which only runs once.

colored bar plot

like image 128
MrFlick Avatar answered Nov 18 '22 00:11

MrFlick