我的数据如下:
d <- data.frame(x=rnorm(40),
y=rnorm(40),
t=rep(sample(1:10, replace = F), times=4),
v=rep(1:4, each=10))
ggplot(d, aes(x=x, y=y)) +
geom_point() +
facet_wrap(~v)
我想添加连接由时间变量(t)排序的点的线(理想情况下带箭头指示方向)。
我该怎么做?
答案 0 :(得分:3)
事实证明使用geom_path
library(dplyr)
library(ggplot2)
d <- data.frame(x=rnorm(40),
y=rnorm(40),
t=rep(sample(1:10, replace = F), times=4),
v=rep(1:4, each=10))
d <- arrange(d, t)
ggplot(d, aes(x=x, y=y)) +
geom_point() +
geom_path(arrow=arrow()) +
facet_wrap(~v)
答案 1 :(得分:2)
正如您在上一个答案中所看到的那样,最后的箭头有时令人困惑,这里有一个在每个点之间添加箭头的提示。
2个解决方案:
d <- data.frame(x=rnorm(40),
y=rnorm(40),
t=rep(sample(1:10, replace = F), times=4),
v=rep(1:4, each=10))
d = d[order(d$t),]
d = d[order(d$v),]
d$y_arrow = c(tail(d$y, n=-1), NA)
d$x_arrow = c(tail(d$x, n=-1), NA)
d$y_arrow[d$t == 10] <- NA
d$x_arrow[d$t == 10] <- NA
ggplot(d, aes(x=x, y=y, group = v)) + geom_point() + facet_wrap(~v) +
geom_path()+ geom_segment(aes(xend=x_arrow, yend=y_arrow),
arrow=arrow(length=unit(0.3,"cm"))) + theme_bw()
d <- data.frame(x=rnorm(40),
y=rnorm(40),
t=rep(sample(1:10, replace = F), times=4),
v=rep(1:4, each=10))
d = d[order(d$t),]
d = d[order(d$v),]
d$y_arrow = c((tail(d$y, n=-1) + head(d$y, n=-1))/2, NA)
d$x_arrow = c((tail(d$x, n=-1) + head(d$x, n=-1))/2, NA)
d$y_arrow[d$t == 10] <- NA
d$x_arrow[d$t == 10] <- NA
ggplot(d, aes(x=x, y=y, group = v)) + geom_point() + facet_wrap(~v) +
geom_path()+ geom_segment(aes(xend=x_arrow, yend=y_arrow),
arrow=arrow(length=unit(0.3,"cm"))) + theme_bw()