2

加载 ggnetwork、network、sna、igraph 和 ggplot:

library(igraph)

library(network)

library(sna)

library(ggnetwork)

library(ggplot2)

创建一个具有五个顶点和两条边的 igraph 对象:

test <- structure(list(5, TRUE, c(0, 3), c(4, 1), c(0, 1),
                 c(1, 0), c(0, 1, 1, 1, 2, 2),
                 c(0, 0, 1, 1, 1, 2), 
                 list(c(1, 0, 1), 
                 structure(list(),
                .Names = character(0)),
                list(name = c("3", "6", "7", "2", "1")),
                list(weight = c(3.30310760667904, 3.55724789915966))), environment),  
                class = "igraph")

检查节点和边的数量:

igraph::ecount(test)
[1] 2

igraph::vcount(test)
[1] 5

下面的代码可以工作(应该不行,注意geom_nodes()中颜色值的个数不对,应该有5个值,但是给了7个):

ggplot(test,aes(x = x, y = y, xend = xend, yend = yend)) + 
       geom_edges(arrow = arrow(), color = 'black') + 
       geom_nodes(size =10, aes(color=1:7/(7))) + 
       scale_color_gradient(low = "green", high = "red")

在此处输入图像描述

如果改为使用 geom_nodes(aes(color= )) 的正确数量的值,则会生成错误:

ggplot(test, aes(x = x, y = y, xend = xend, yend = yend)) +
      geom_edges(arrow = arrow(), color ='black') + 
      geom_nodes(size =10, aes(color=1:5/(5))) + 
      scale_color_gradient(low = "green", high = "red")

Error: Aesthetics must be either length 1 or the same as the data (7): colour

注意 geom_nodes 似乎需要 |color| = |节点| + |edges|,这是为什么呢?有没有解决的办法?如果通过了 7 种颜色,它如何决定将哪 5 种用于节点颜色?

4

0 回答 0