It depends on what you mean by "degree of centrality": a node in a graph has a degree, which is the number of links it has to other nodes; in directed graphs, this is the sum of in-degree and out-degree.
Further, you can compute a measure of centrality for a node, which essentially tries to answer the question how "well connected", "embedded" or simply "central" a node is in the graph (I'm well aware that this is cutting many notions of centrality short, but this is StackOverflow, not Wikipedia). There are quite a few different kinds of centrality, that each take a different approach. Again, Wikipedia or your favourite book on graph theory is your friend here.
Here is some code that illustrates both how to compute the degree of a node, and a measure of centrality:
library(igraph)
df <- data.frame(
"from" = c("Mickey", "Minnie", "Huey", "Donald", "Scrooge"),
"to" = c("Daffy", "Donald", "Minnie", "Minnie", "Minnie")
)
g <- graph_from_data_frame(df, directed = TRUE) # or FALSE
g <- set_edge_attr(g, name = "tnum", value = c(12345, 34567, 21345, 22345, 22456))
plot.igraph(g, edge.label = edge_attr(g, "tnum"))
degree(g)
centralization.betweenness(g)
If you require other measures of centrality, searching the igraph manual for centrality
or centralization
will be the way to go.
If you want to colorize your graph based on these centrylity measures, have a look at this code and consult the excellent igraph-manual if anything is unclear:
library(igraph)
df <- data.frame(
"from" = c("Mickey", "Minnie", "Huey", "Donald", "Scrooge"),
"to" = c("Daffy", "Donald", "Minnie", "Minnie", "Minnie")
)
# create an igraph object from the dataframe, which essentially is a list
# of edges between nodes
g <- graph_from_data_frame(df, directed = TRUE) # or FALSE
# each edge receives "tnum" as an attribute
g <-
set_edge_attr(g,
name = "tnum",
value = c(12345, 34567, 21345, 22345, 22456))
# calculate betweenness of nodes and store it in an attribute "color" of the
# vertices. The color-attribute is treated specially when plotting graphs.
V(g)$color <- betweenness(g)
plot.igraph(g,
# plot edge labels from the "tnum" attribute
edge.label = edge_attr(g, "tnum"),
# specify the palette of colours to use when plotting vertices
palette = heat.colors(n = 99))
# same as above; we multiply by 100 to make sure all values are > 0, otherwise
# the colour will be interpreted as 0 (usually, white)
V(g)$color <- (eigen_centrality(g)$vector) * 100
# assign edge weights based on the last digit of "tnum"
E(g)$weight <- E(g)$tnum %% 10
plot.igraph(
g,
edge.label = edge_attr(g, "tnum"),
edge.width = E(g)$weight,
edge.arrow.size = .8,
palette = heat.colors(n = 99)
)