2016-09-26 107 views
0

我想根據值> 5和值< -5和它們之間的值爲我的繪圖提供不同的顏色(顏色範圍)。就像附加的圖像一樣,在圖像中,只有2種顏色超過5 /小於5以及它們之間的值。如何給顏色範圍散點圖的上下值

我的代碼是:

ggplot(data, aes(S1, S2, color=abs(S1-S2)>5)) +geom_point()+ smoother 

Scatter plot image

+0

'color = cut((S1-S2),breaks = c(-Inf,-5,5,+ Inf))' – JasonAizkalns

+0

感謝jason,我該如何根據計數來創建圖例,例如: ** g> 5:80 ** – user3616494

回答

0

這裏是ggplot之前創建對應於色基團的新的變量的溶液:

set.seed(1) 
df = data.frame(x = rnorm(1000,1,10)) 
df$y = df$x + rnorm(1000,1,5) 

df$col = NA 
df$col[(df$x - df$y) > 5] = "g1" 
df$col[(df$x - df$y) < 5 & (df$x - df$y) > -5] = "g2" 
df$col[(df$x - df$y) < -5] = "g3" 

ggplot(df, aes(x, y, color = col)) + geom_point() 

enter image description here

EDIT
如果你想標記傳說與觀測的數量,並選擇顏色:

library(plyr) 
df_labels = ddply(df, "col", summarise, n = n()) 

ggplot(df, aes(x, y, color = col)) + geom_point() + 
scale_color_manual(labels = df_labels$n, values = c("g1" = "red", "g2" = "blue", "g3" = "green")) 

enter image description here

+0

感謝您的回答,我該如何計算圖例中的數字?像這樣,例如** g1:87 **。 – user3616494

+0

我剛編輯我的答案來修改標籤。 – bVa

0

確保您的顏色計算得到3個值的結果:

ggplot(data, aes(S1, S2, color=factor(ifelse(S1-S2>5,1,ifelse(S2-S1>5,2,4)) , labels = c("less","more","same")))) +geom_point() 

或者在繪圖之前,在腳本的另一個步驟中進行此操作。