我正在尝试制作一个网络图,其中节点将使用ggnet按类别着色。
示例代码:
install.packages("GGally")
library(GGally)
devtools::install_github("briatte/ggnet")
library(ggnet)
library(network)
library(sna)
library(ggplot2)
#input data
n1 = data.frame(family = c(rep("fam.A",3), rep("fam.B",3), rep("fam.C",2)),member = c("a1", "a2", "a3", "b1", "b2","b3", "c1", "c2"))
n2 = data.frame(family = c(rep("fam.A",3), rep("fam.B",3), rep("fam.D",2)),member = c("a1", "a4", "a5", "b4", "b5","b6", "d1", "d2"))
n = rbind(n1, n2)
n$category = c("common", rep("type-n1",7), rep("type-n2",8))
#make network
net = network(as.matrix(n[,1:2]), directed = FALSE)
ggnet2(net, label = TRUE, alpha = 1)
输出看起来像这样。但是,我想按照我的类别"common", "type-n1", "type-n1"
对颜色节点进行着色。
答案 0 :(得分:1)
我通过以下方式解决了这个问题:
e2 = n
net2 = network(e2, directed = TRUE)
x2 = data.frame(Type = network.vertex.names(net2))
x2 = factor(c("common", rep("Type-n1",6), rep("Type-n2",8), rep("fam", 4)))
net2 %v% "color" = as.character(x2)
y2 = RColorBrewer::brewer.pal(9, "Set1")[ c(3, 1, 9,6, 7) ]
names(y2) = levels(x2)
ggnet2(net2, color = "color", palette = y2, alpha = 0.75, size = 5,
edge.alpha = 0.5, label = TRUE)
产量: