49

I want to plot a graph with different colors based on values. I wrote the below code,

np_graph <- data.frame(C1 = -5:5, C2 = -5:5)
x=np_graph2$C1
y=np_graph2$C2
plot(x,y,xlab="PC1",ylab="PC2")

Now, if the value of X is >0, then that value should be in green (in the graph). if the value of Y is >0, then that value should be in red (in the graph).

Can some one help me in this?

mnel
  • 113,303
  • 27
  • 265
  • 254
I am
  • 1,057
  • 5
  • 14
  • 21

2 Answers2

114

The argument col will set the colours, you could use this in conjunction with an ifelse statement. See ?plot for more details.

# using base plot
plot(x,y,xlab="PC1",ylab="PC2", col = ifelse(x < 0,'red','green'), pch = 19 )

enter image description here

To do the same thing in ggplot2.

#using ggplot2
library(ggplot2)
ggplot(np_graph) + geom_point(aes(x = C1, y = C2, colour = C1 >0)) +
  scale_colour_manual(name = 'PC1 > 0', values = setNames(c('red','green'),c(T, F))) +
  xlab('PC1') + ylab('PC2')

enter image description here

mnel
  • 113,303
  • 27
  • 265
  • 254
  • 5
    +1 very nice. Also for showing the newby how to make a reproducible example. – Andrie Aug 07 '12 at 05:00
  • @mnel very nice answer. Although I have a question to you. If I want to put up range of values like x > 1 & y > 2 then green color, x < 1 & y > 2 then red color and the rest of the points in gray color. How will I be able to accomplish it? – Akshay Jul 09 '13 at 14:51
  • 4
    @aarn -- a couple of nested `ifelse` statements should do it. eg ` col = ifelse(x>1&y>1,'red', ifelse(x<1&y>2,'green','grey'))` – mnel Jul 09 '13 at 23:16
  • 1
    @mnel what if you have three conditions? – bvowe Nov 27 '19 at 17:17
13

Alternatively, in ggplot2, you can set a new column "Color" based on the ifelse statement and then use scale_color_identity to apply those color on the graph:

np_graph %>% mutate(Color = ifelse(C1 > 0, "green", "red")) %>%
  ggplot(aes(x = C1, y= C2, color = Color))+
  geom_point()+
  scale_color_identity()

enter image description here

dc37
  • 15,840
  • 4
  • 15
  • 32