R通过顶点隶属关系为GGally着色边缘

时间:2018-09-21 13:10:54

标签: r graph ggally

我正在尝试创建一个列表,以根据它们连接到的顶点的分组来为图形的边缘着色。如果边缘连接同一组的两个成员,则边缘具有其颜色。如果边缘位于不同组的成员之间,则边缘应为灰色。这是我的代码:

mnet = rgraph(10, mode = "graph", tprob = 0.5)
rownames(mnet)<-letters[1:10]
colnames(mnet)<-letters[1:10]
net = network(mnet, directed = FALSE, ignore.eval = FALSE, names.eval = "strength")
phono<-data.frame(letters=letters[1:10],phono=c("vowel", "consonant","consonant","consonant","vowel","consonant","consonant","consonant","vowel", "consonant"))
table(phono)
net %v% "phono" <- as.character(phono$phono)
nnet<-matrix(0, 10, 10)
for (i in 1:10){
  for (j in 1:10){
    nnet[i,j] = ifelse(phono$phono[phono$letters %in% rownames(mnet)[i]]==phono$phono[phono$letters %in% colnames(mnet)[j]],
                       as.character(phono$phono[phono$letters %in% rownames(mnet)[i]]),
                       "grey50")
  }
}
ggnet2(net, color = "phono", palette = "Set2", label = "phono", edge.color = unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])

我对我的R代码中间的双重循环不满意。有没有更好的方法来做我想做的事情?这是我最前面的问题的补充,更多地试图理解为什么“外部”不起作用。

此外,代码通常无法正常工作,但让我们一次解决一个问题。即使 length(unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])==length(net %e% "strength")

谢谢。

1 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

enter image description here

代码:

# build graph
net <- sna::rgraph(10, mode = "graph", tprob = 0.5)
net <- network::network(net, directed = FALSE)

# vowels and consonants
phono <- c("v", "c", "c", "c", "v", "c", "c", "c", "v", "c")
names(phono) <- letters[1:10]

# extract edgelist, identify same-letter-type ties
edges <- as.edgelist(net)
k <- ifelse(phono[ edges[, 1] ] == phono[ edges[, 2] ], phono[ edges[, 1] ], NA)

# color ties using `Set2` colors
k[ is.na(k) ] <- "x"
k <- c("c" = "#66C2A5", "v" = "#FC8D62", "x" = "grey50")[ k ]

set.edge.attribute(net, "tie.type", k)
GGally::ggnet2(
  net,
  color = phono[ network.vertex.names(net) ],
  palette = "Set2",
  label = phono[ network.vertex.names(net) ],
  edge.color = "tie.type",
  edge.size = 1
)