2016-06-07 66 views
7

我在R中使用ggplot2來產生由連續線連接的數據框中的有序點的散點圖。在這一行上,我想放置幾個箭頭來顯示數據框中點的順序。如下圖所示,我可以在每個相鄰點之間放置一個箭頭,但是當我添加更多點時,該圖會變得擁擠並帶有箭頭和雜亂。有沒有辦法讓我可以在每兩個,三個,四個相鄰的點之間放置箭頭?控制箭頭的數量

library(ggplot2) 
library(grid) 

b = c(1,2,3,6,7,5,4,3,2,3,4,6,8,9,9,8,9,11,12) 
c = c(2,3,2,4,4,6,8,7,5,4,3,5,9,9,8,8,10,11,15) 
df = data.frame(b, c) 

ggplot(df, aes(x=b, y= c)) + 
    geom_point() + 
    geom_segment(aes(xend=c(tail(b, n=-1), NA), yend=c(tail(c, n=-1), NA)), 
       arrow=arrow(length=unit(0.4,"cm"), type = "closed")) 

示例圖: enter image description here

+1

您可以使用數據的子集箭頭。 – zx8754

回答

2

這裏是我的建議

# add columns which have values only in rows you want arrows for 
df$d<-NA 
df$d[2:4]<-df$b[2:4] 
df$e<-NA 
df$e[2:4]<-df$c[2:4] 
# and then plot 
ggplot(df, aes(x=b, y= c)) + 
    geom_point() + 

    geom_segment(aes(xend=c(tail(b, n=-1), NA), yend=c(tail(c, n=-1), NA)), 
       )+ 
    geom_segment(aes(xend=c(tail(d, n=-1), NA), yend=c(tail(e, n=-1), NA)), 
       arrow=arrow(length=unit(0.4,"cm"),type = "closed") 
       ) 

enter image description here

+1

是的,我同意這是一個解決方案,我想這是與圖形語法中的分層保持一致,但在數據框中部分重複數據列似乎是一種恥辱。 – RoachLord