2
我想製作一個圖表,如果x的值大於y的值,那麼該點就是一種顏色,如果它小於y,則是另一種顏色。如何在R中使用ggplot製作一個散點圖,其中顏色根據y> x或y <x而變化?
下面是代碼,我想出了:
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
我的問題,我認爲是循環,它給了我一堆不能用的geom_point()函數中使用的NAS。 謝謝。
如果您將'na.rm = T'添加到您的'geom_point'調用中,該怎麼辦?見[這裏](http://docs.ggplot2.org/0.9.3.1/geom_point.html)。 –
是否這樣? 'ggplot(df,aes(C1,C2))+ geom_point(color = ifelse(df $ C1 <= df $ C2,'blue','green'))' – rawr
謝謝!你的線路工作,不需要循環之前! – KatherineD