在 R 中的 igraph 图上定位边缘标签

Position edge labels on igraph plot in R

我正在尝试使用 igraph 绘制几个变量之间的因果图。下面是我的代码,基本上是图表中我想要的所有内容,除了我无法让其他两个边缘标签向上移动到边缘上方,例如连接 "stability" 到 "status" 的标签。

ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("-", "-", "-")


nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)


study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = 0.5,
     edge.label.cex = 3,
     edge.label.color = "black")

您必须为每个标签指定 y 坐标,即 edge.label.y = c(0.6, 0.2, -0.5) 。我稍微更改了您的代码,以便您可以看到哪个标签是哪个,即 association <- c("A", "B", "C")

完整代码:

library(igraph)

ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("A", "B", "C")


nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)


study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = c(0.6, 0.2, -0.5), # specify the y-coordinate for each label
     edge.label.cex = 3,
     edge.label.color = "black")

这将导致: