Plot with conditional colors based on values in R

Viewed 122515

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?

2 Answers

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

Related