2015-12-06 47 views
2

我有以下代碼繪製點並在它們之間畫線。基於斜率在ggplot中更改線條顏色

ggplot (data = subset(df, vowel == "O" & gender == "f"), aes (x = time, y = val, color = formant)) + 
     geom_point()+ 
     geom_line(aes(group=interaction(formant, number))) 

它產生這樣的:

enter image description here

有一種方法,以這些組由彩色/線類型爲負斜率與這些線中的正斜率?

編輯: 這裏是我的數據:

number <- c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) 
formant <- c("F2", "F2", "F2", "F2", "F2", "F2", "F3", "F3", "F3", "F3", "F3", "F3") 
time <- c(50, 50, 50, 99, 99, 99, 50, 50, 50, 99, 99, 99) 
val <- c(400, 500, 600, 450, 550, 650, 300, 400, 500, 250, 350, 450) 

我要顯示在val超過time通過formantnumber分組的價值變動。所以當我實現答案時,它告訴我我有一個不兼容的大小,我認爲這與它按數字分組的事實有關。

回答

8

你還沒有提供樣本數據,所以這是一個風格化的例子。總體思路是創建一個變量,測試斜率是否大於零,然後將其映射到顏色審美。在這種情況下,我使用dplyr鏈接運算符(%>%)爲了在ggplot的調用中動態添加斜率。 (我去計算斜率的麻煩,但你也可以同樣測試是否value[t==2] > value[t==1]代替。)

library(dplyr) 

# Fake data 
set.seed(205) 
dat = data.frame(t=rep(1:2, each=10), 
       pairs=rep(1:10,2), 
       value=rnorm(20), 
       group=rep(c("A","B"), 10)) 

dat$value[dat$group=="A"] = dat$value[dat$group=="A"] + 6 

ggplot(dat %>% group_by(pairs) %>% 
     mutate(slope = (value[t==2] - value[t==1])/(2-1)), 
     aes(t, value, group=pairs, linetype=group, colour=slope > 0)) + 
    geom_point() + 
    geom_line() 

enter image description here

UPDATE:基於您的評論,這聽起來像你只需要將number映射到審美或使用面。下面是使用您的樣本數據琢面版:

df = data.frame(number, formant, time, val) 

# Shift val a bit 
set.seed(1095) 
df$val = df$val + rnorm(nrow(df), 0, 10) 

ggplot (df %>% group_by(formant, number) %>% 
      mutate(slope=(val[time==99] - val[time==50])/(99-50)), 
     aes (x = time, y = val, linetype = formant, colour=slope > 0)) + 
    geom_point()+ 
    geom_line(aes(group=interaction(formant, number))) + 
    facet_grid(. ~ number) 

enter image description here

下面是映射number的點標記的大小的另一種選擇。這看起來不太好,但僅用於說明如何將變量映射到圖中不同的「美學」(顏色,形狀,大小等)。

ggplot (df %>% group_by(formant, number) %>% 
      mutate(slope=(val[time==99] - val[time==50])/(99-50)), 
     aes (x = time, y = val, linetype = formant, colour=slope > 0)) + 
    geom_point(aes(size=number))+ 
    geom_line(aes(group=interaction(formant, number))) 
+0

謝謝!但是,這並沒有結束我的數據,因爲它必須由任意數字分組。對不起,我沒有發佈我的數據最初,我會寫代碼重新創建它。 – Lisa