【问题标题】:Match vertex and edge color in igraph匹配igraph中的顶点和边缘颜色
【发布时间】:2020-08-19 03:21:48
【问题描述】:

我有一个大型数据集,我想使用 igraph 用网络图表示。我只是不明白如何获得正确的颜色。是否可以获得边缘颜色与顶点颜色相同的 igraph 图?在下面的示例中,我想根据状态“采样”或“未采样”为顶点和边缘着色。另一个问题是所有的边缘都没有出现在igraph上,我不明白为什么

到目前为止我的代码是:

d <- data.frame(individual=c(1:10), mother_id = c(0,0,0,0,0,1,3,7,6,7), father_id = c(0,0,0,0,0,4,1,6,7,6) , generation = c(0,0,0,0,0,1,1,2,2,2), status=c("sampled","unsampled","unsampled","sampled",'sampled',"sampled","unsampled","unsampled","sampled",'sampled'))

#Just some settings for layout plot
g <- d$generation
n <- nrow(d)
pos <- matrix(data = NA, nrow = n, ncol = 2)
pos[, 2] <- max(g) - g
pos[, 1] <- order(g, partial = order(d$individual, decreasing = TRUE)) - cumsum(c(0, table(g)))[g + 1]

#Plotting the igraph
G <- graph_from_data_frame(d)
plot(G, rescale = T, vertex.label = d$individual, layout = pos,
edge.arrow.mode = "-",
vertex.color = d$status,
edge.color = d$status,
asp = 0.35)

我的问题有点类似于这个问题,但我想用 igraph 包来做。 Ggraph node color to match edge color

感谢您的帮助

【问题讨论】:

  • 一般来说,一条边可以连接两个不同颜色的节点。在这种情况下,您如何选择颜色?还是这种情况总是排除在您的数据中?
  • 该图代表了家谱树的不同世代。第一代是第一层,第二代是第二层,以此类推。想法是用与上层节点相同的颜色对边缘进行着色。谢谢你的帮助
  • 如果您按照下面的示例组织数据,那么匹配颜色将非常容易。我不确定您希望边缘在哪里。图是有向图还是无向图? id 6 是否接收来自 1 和 4 的链接?

标签: r colors igraph


【解决方案1】:

如果您plot(G),您将看到来自数据框对象的图形很可能不是您所期望的。这就是为什么您看不到所有边缘的原因(即根本不使用列father_id)。

默认情况下,igraph 将第一列为“from”,第二列为“to”。这就是为什么你会看到 1to0、2to0 等等。

您可以通过传入两个对象来解决此问题,一个带有边及其属性,一个带有节点及其属性。 我不太清楚边缘应该在哪里。但是,您的代码应如下所示:

dd <- read.table(text = "
from to type
1 6 A
3 7 B
7 8 A
6 9 B
7 10 A
4 6 B
1 7 A
6 8 B
7 9 B
6 10 A ", header=T )

nodes <- data.frame(id=unique(c(dd$from, dd$to)) )
nodes$type <- sample(LETTERS[1:2], 8, replace = T  )
nodes$x <- c(8,3,5,7,1,2,4,10) # this if for the layout
nodes$y <- c(1, 2, 4, 5, 6, 8, 5, 7)

    nodes
  id type  x y
1  1    B  8 1
2  3    A  3 2
3  7    B  5 4
4  6    A  7 5
5  4    A  1 6
6  8    B  2 8
7  9    A  4 5
8 10    A 10 7

G <- graph_from_data_frame(dd, vertices = nodes ) # directed T or F?

V(G)$color <- ifelse( V(G)$type == "A", "pink", "skyblue")
E(G)$color <- ifelse( E(G)$type == "A", "pink", "skyblue")

edge_attr(G)
vertex_attr(G)
plot(G)

【讨论】:

    最近更新 更多