Rashedul Islam
Rashedul Islam

Reputation: 939

ggnet adding node color by category

I am trying to make a network plot where nodes will be colored by categories using ggnet.

Example code:

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)

The output looks like this. However, I want to color the nodes by categories I have e.g, "common", "type-n1", "type-n1".

enter image description here

Upvotes: 0

Views: 819

Answers (1)

Rashedul Islam
Rashedul Islam

Reputation: 939

I have solved this by:

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)

Yielding:

enter image description here

Upvotes: 1

Related Questions