2017-09-25 76 views
0

我想改變線段的顏色是否大於它之前的點。我在這裏做錯了什麼?顏色ggplot線的基礎上增加或減少

例子:

from [1,4] to [2,5] would be green because the y value is increasing. 
from [1,4] to [2,1] would be red because the y value is decreasing. 

我的代碼:

set.seed(42) 
df<-NULL 
df$x<-rnorm(10,0,10) 
df$y<-rnorm(10,0,10) 
df$colors<-cbind(lapply(1:length(df$x),function(i){ 
    ifelse(df$x[i]>df$x[i-1],"#CC6666","#9999CC") 
})) 
df<-data.frame(df) 


ggplot()+ 
    geom_line(aes(x=df$x,y=df$y),size=1.5,colour=df$color)+ 
    scale_color_manual(values=df$color) 

回答

1

將這樣的事情對你的工作,我重新安排你的榜樣數據一點,但我們可以用geom_segment()dplyr::lead()得到顏色匹配正確,並有一點ggplot破解,使標籤再次漂亮,並溝:NA:

set.seed(42) 
df <- data.frame(x = rnorm(10,0,10), 
        y = rnorm(10,0,10)) 

# base R 
df <- df[order(df$x),] 
df$color <- sapply(1:nrow(df), function(i) df$y[i] > df$y[i+1]) 
df$group <- "1" 

library(tidyverse) 
df <- arrange(df, x) %>% 
    mutate(color = y > lead(y), 
      group = "1") # group everything togther or else we get two lines 

ggplot()+ 
    geom_path(data = df, 
       aes(x=x, y=y, color = color, group = group),size=1.5) + 
    scale_color_manual(values = c("#CC6666","#9999CC"), na.value = "white", 
         labels = c("increase", "decrease", "")) 

enter image description here

+0

這很好,但即時通訊組的困惑。如果值較大,您可以安排變量,然後進行變異以創建新列「1」。如果值較小,則只是自動分配一個不同的組? – Rilcon42

+0

該組只是在那裏,因爲默認情況下ggplot與嘗試根據美學(如果定義)組合,所以我們只使用「1」作爲粘合劑,以確保它們保持在同一行。這個安排就是這樣,我們正在做相對於x軸順序的適當的「i + 1」comparrisons – Nate