我在R中使用ggplot2来生成由连续线连接的数据帧中有序点的散点图。在这一行,我想放置几个箭头,显示数据框中点的顺序。我可以在每个相邻的点之间放置一个箭头,如下所示,但随着我添加更多的点,图形变得拥挤的箭头和凌乱。有没有办法让我可以在每个2,3,4相邻的点之间放置箭头?
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"))
答案 0 :(得分: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")
)