要使用igraph 执行此操作,我认为您需要深入研究plot.igraph 函数,找出它为顶点之间的弯曲边缘生成贝塞尔曲线的位置,然后使用插值沿这些边缘获取点.有了这些信息,您可以沿着图形边缘绘制箭头线段。
这里有一种不同的方法,它并不完全符合您的要求,但我希望它可以满足您的需求。而不是igraph,我将使用ggplot2 以及GGally 包中的ggnet2 函数。
基本的方法是获取每个图形边缘的端点坐标,然后沿着我们将绘制箭头段的每条边缘插入点。请注意,边缘是直线,因为ggnet2 不支持弯曲边缘。
library(ggplot2)
library(GGally)
# Create an adjacency matrix that we'll turn into a network graph
m = matrix(c(0,1,0,0,
0,0,1,0,
1,0,0,1,
0,0,0,0), byrow=TRUE, nrow=4)
# Plot adjacency matrix as a directed network graph
set.seed(2)
p = ggnet2(network(m, directed=TRUE), label=TRUE, arrow.gap=0.03)
图表如下所示:
现在我们要沿每条边添加箭头。为此,我们首先需要找出每条边的端点坐标。我们可以使用 ggplot_build 从图形对象本身获取它:
gg = ggplot_build(p)
图形数据存储在gg$data:
gg$data
[[1]]
x xend y yend PANEL group colour size linetype alpha
1 0.48473786 0.145219576 0.29929766 0.97320807 1 -1 grey50 0.25 solid 1
2 0.12773544 0.003986273 0.97026602 0.04720945 1 -1 grey50 0.25 solid 1
3 0.02670486 0.471530869 0.03114479 0.25883640 1 -1 grey50 0.25 solid 1
4 0.52459870 0.973637028 0.25818813 0.01431760 1 -1 grey50 0.25 solid 1
[[2]]
alpha colour shape size x y PANEL group fill stroke
1 1 grey75 19 9 0.1317217 1.00000000 1 1 NA 0.5
2 1 grey75 19 9 0.0000000 0.01747546 1 1 NA 0.5
3 1 grey75 19 9 0.4982357 0.27250573 1 1 NA 0.5
4 1 grey75 19 9 1.0000000 0.00000000 1 1 NA 0.5
[[3]]
x y PANEL group colour size angle hjust vjust alpha family fontface lineheight label
1 0.1317217 1.00000000 1 -1 black 4.5 0 0.5 0.5 1 1 1.2 1
2 0.0000000 0.01747546 1 -1 black 4.5 0 0.5 0.5 1 1 1.2 2
3 0.4982357 0.27250573 1 -1 black 4.5 0 0.5 0.5 1 1 1.2 3
4 1.0000000 0.00000000 1 -1 black 4.5 0 0.5 0.5 1 1 1.2 4
在上面的输出中,我们可以看到gg$data[[1]] 的前四列包含每条边的端点坐标(并且它们的有向图顺序正确)。
现在我们有了每条边的端点,我们可以在两个端点之间插入点,我们将在端点上绘制带有箭头的线段。下面的函数会处理这个问题。它获取每条边的端点数据框,并返回对绘制 n 箭头段的geom_segment(每个图形边一个)的调用列表。然后可以将geom_segment 调用列表直接添加到我们的原始网络图中。
# Function that interpolates points between each edge in the graph,
# puts those points in a data frame,
# and uses that data frame to return a call to geom_segment to add the arrow heads
add.arrows = function(data, n=10, arrow.length=0.1, col="grey50") {
lapply(1:nrow(data), function(i) {
# Get coordinates of edge end points
x = as.numeric(data[i,1:4])
# Interpolate between the end points and put result in a data frame
# n determines the number of interpolation points
xp=seq(x[1],x[2],length.out=n)
yp=approxfun(x[c(1,2)],x[c(3,4)])(seq(x[1],x[2],length.out=n))
df = data.frame(x=xp[-n], xend=xp[-1], y=yp[-n], yend=yp[-1])
# Create a ggplot2 geom_segment call with n arrow segments along a graph edge
geom_segment(data=df, aes(x=x,xend=xend,y=y,yend=yend), colour=col,
arrow=arrow(length=unit(arrow.length,"inches"), type="closed"))
})
}
现在让我们运行函数将箭头添加到原始网络图
p = p + add.arrows(gg$data[[1]], 15)
图表如下所示: