基于图中条件的颜色节点

时间:2017-06-18 14:07:33

标签: r igraph

我有这个数据集:

id  |  user_id  | follower_user_id
1   |     1     |   2
2   |     1     |   3
3   |     3     |   1

并且我希望值等于0的节点具有红色,并且值等于或大于1的节点具有红色,并且它们的圆圈根据值的大小而更大。

是否可以使用igraph进行制作?

带边的数据集。输入数据帧:

来自评论的

编辑

我根据书籍和引文制作了这个数据集。书籍=节点和引文=链接。每本书都是独一无二的,并有引文。引用可能是不止一本书的共同点。这就是为什么ie link1在多列中的原因。链接44直到link100是引用,但仅存在于book1中,但不存在于其他书籍中。因为书籍和引文都有单词作为标题,并且为了制作图表,它可能没有帮助我将书名改为具有编号和引用的节点到编号的链接。多个书籍共有的引文具有相同的ID ielink1

df <- structure(list(name = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L, 2L), .Label = c("node1", "node10", "node2", "node3", 
"node4", "node5", "node6", "node7", "node8", "node9"), class = "factor"), 
    value = c(100L, 14L, 2L, 0L, 25L, 0L, 0L, 43L, 7L, 0L)), .Names = c("name", 
"value"), class = "data.frame", row.names = c(NA, -10L))

在图中,每个节点由圆圈描绘,其直径与频率数成正比。 列名是节点,每行中的链接都是连接元素。

如何向链接节点提供黄色和0频率节点为红色节点?

1 个答案:

答案 0 :(得分:2)

# As the links are in the same row index under each node they
# can be converted to 1/0 (presence of link/not) by 
# the links being missing or otherwise
# From this you can create adjacency matrix between the nodes by
# taking the crossproduct
x <- as.matrix(df)
x <- !is.na(x)
adjMat <- crossprod(x)

library(igraph)

# Read in the adjacency matrix
g = graph_from_adjacency_matrix(adjMat, mode="undirected", weighted=TRUE, diag=FALSE)

# For your original question
# set colour by setting V(g)$color attribute
# if diagonal is nonzero vertex colour is red else blue
V(g)$color <- ifelse(diag(adjMat), "red", "blue")
# Similarily for size: here vertex size is set to the number of 
# citations each book has (the diagonal of adj matrix)
V(g)$size <- diag(adjMat)

# Plot setting the edge weight equal to the number of shared links
plot(g, edge.width=E(g)$weight/2)

# If you want to remove the nodes with zero citations
# probably an igraph function to do this but you can do it manually
g1 <- g - paste0("node", which(diag(adjMat)==0))
plot(g1, edge.width=E(g1)$weight/2)