2010-08-06 50 views
11

我想創建一個geom_path(),該箭頭指向路徑中的下一個位置。需要的示例:使用帶ggplot2的箭頭()

我可以繪製路徑,沒有問題,例如:

df <- (x=1:12, y=20:31, z=1:12) 
p <- ggplot(df, aes(x=x, y=y)) 
p + geom_point() + geom_path() 

現在想什麼,我能夠做的是劇情,在路徑指向箭頭從一個元素到下一個。

如果您能告訴我如何平滑從路徑中的一個元素到下一個元素的線條,可能會出現額外的標記。

回答

16

geom_segment有一個arrow參數。這裏有一個簡單的例子:

library(grid) # needed for arrow function 

p <- ggplot(df, aes(x=x, y=y)) + 
    geom_point() + 
    geom_segment(aes(xend=c(tail(x, n=-1), NA), yend=c(tail(y, n=-1), NA)), 
        arrow=arrow(length=unit(0.3,"cm"))) 

library(grid)是需要arrow()功能,見here

+0

geom_segment像一個魅力工作,但我想知道爲什麼你選擇geom_segment去看起來像geom_path的主要功能? – 2010-08-06 18:38:23

+1

'geom_path'(或'geom_line')不會繪製每個線段的箭頭,最後一個點的位置只有一個箭頭。 – rcs 2010-08-06 20:21:19

+0

感謝您的解釋rcs。 – 2010-08-09 17:06:07