I would like some help getting started in creating a network in igraph in R
.
My data looks like this:
data <- data.frame(Country = c("Argentina", "Bolivia", "Chile", "France", "Guam", "US"), Counts = c(2,8,1,5,3,35))
Where the counts column is the count of how many times these countries appeared in a specific search.
Every tutorial I am reading on igraph has a way to graph nodes and edges. With edges usually containing a from and to column. But in this dataset, the countries are not linked. I just need help getting this code started. I have included a picture on what my end result should look like - with the thickness of the lines being proportional to the counts column. Is this possible?
CodePudding user response:
As pointed out by @Vida, we need to construct a center.
library(igraph)
nations <- data.frame(Country = c("Argentina", "Bolivia", "Chile", "France", "Guam", "US"),
Counts = c(2,8,1,5,3,35),
Population = c(45.195, 11.673, 19.116, 65.625, 0.172, 332.403)
)
center <- setNames(data.frame("c",2,0), names(nations))
vtx <- rbind(center, nations)
rel <- data.frame( from = head(vtx$Country, 1),
to = tail(vtx$Country),
width = tail(vtx$Counts)
)
## >?graph_from_data_frame, read the docs.
g <- graph_from_data_frame(rel, directed = FALSE, vtx )
vertex_attr_names(g)
g
Plotting a nice graph is an art in itself. See for example a recent query: How can I make edge betweenness with igraph in R?
## >?plot.igraph, read the docs.
cols <- c("white", "green", "black", "brown", "blue", "yellow", "purple")
V(g)$color <- "white"
V(g)$size <- c(2, rep(40, nrow(vtx)-1))
V(g)$frame.color <- cols
V(g)$frame.width <- 4
E(g)$color <- tail(cols)
plot(g, layout=layout_as_star)
## An alternative is to change the vertex size.
size <- (rank(V(g)$Population) - 1) * 5
dev.new(); plot(g, layout=layout_as_star, vertex.size = size , edge.width=4)