6

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

thelatemail
  • 91,185
  • 12
  • 128
  • 188
user3720887
  • 719
  • 1
  • 11
  • 18

1 Answers1

17

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295