How can i use ggplot in R to make a scatterplot where the colour varies depending on if y>x or y<x?

Question

I would like make a graph where if the value of x is greater than the value of y, the point is a colour and if it is less than y it is another color.

Here is the code I've come up with:

df = read.table(text = 
          "C1         C2 
        2003          2030
        2001          2301
        2005          2002
        2333          2003
        5466          4444
        2000          2002
        2222          2223
        1000          2032
    ", sep = "", header = TRUE)
p2 <- vector()
p3 <- vector()
for (i in 1:length(A$C1))
  {if(A$C2[i]>=A$C1[i]) {
  p2[i] <- A$C1[i]
}else
if(A$C2[i]<=A$C1[i]){
  p3[i] <- A$C1[i]
}
}
p <- ggplot(data=Movie, aes(x=C1, y=C2))+ 
  ylab("C2")+
  xlab("C1")+
  ggtitle("C1 on C2")+
  geom_smooth(method = lm)+
  geom_point(aes(x=p2), color="blue")+
  geom_point(aes(x=p3), color="green")
p

My problem I think is that loop, it gives me a bunch of NAs that cannot be used by the geom_point() function. Thank you.


Show source
| R   | graph   | ggplot2   2016-11-07 03:11 1 Answers

Answers ( 1 )

  1. 2016-11-07 03:11

    It's easier than you think.

    df <- transform(df,P=C1>C2)
    ggplot(df, aes(x=C1, y=C2, colour=P))+ 
      geom_smooth(method = lm,aes(group=1))+
        geom_point()+
        scale_colour_manual(values=c("blue","green"))+
        geom_abline(intercept=0,slope=1,lty=2)
    

    @rawr's solution

    ggplot(df, aes(C1, C2)) + 
      geom_point(colour = ifelse(df$C1 <= df$C2, 'blue', 'green')) 
    

    works too, but it won't give you a legend (in case you want one), and it won't scale quite as well (e.g. if you wanted to divide into three or four groups it would still be possible, but would be progressively more annoying).

◀ Go back