data science

Colouring Nodes According to Centrality – R

This R function will draw a graph and then colour the nodes according to centrality.

There are three colours, red for high centrality, purple for medium centrality, and blue for low centrality.

Node centrality was calculated using the betweenness( ) function in the igraph R library. It was then normalised manually so that we are left with an index from 0 to 1, where 1 is maximum centrality and 0 is minimum.

Colours were then applied for each third, so that nodes with centrality ranging from 0 to 0.333 were coloured blue, from 0.334 to 0.666 were coloured purple, and from 0.667 to 1.000 were coloured red.

Building The Graph

Practically any network graph can be used with the function, but I started with a random graph using the ) function.

my_g <-,1/30)

Where 100 is the number of nodes, and 1/30 is the probability of drawing edges.

The Function

This is where the magic happens…

color.cent.graph <- function(g) {

	# first thing is to get the centrality vector
	vec_bet_cent <- betweenness(g)

	# normalise centrality
	vec_norm_cent <- vec_bet_cent/max(vec_bet_cent)

	# create a data frame with normalised centrality
	g_df <- data.frame('Cb'=vec_norm_cent)

	# add a column for colour
	g_df$'color' <- 'NA'

	# now we add the colour according to centrality
    # if you want to use different colours, this is
    # where you change things
	g_df$'color'[(g_df$'Cb')<=0.333] <- 'blue'
	g_df$'color'[(g_df$'Cb')>0.333] <- 'purple'
	g_df$'color'[(g_df$'Cb')>0.666] <- 'red'

	# then apply colours to graph
	V(g)$color <- g_df$'color'

    # now draw the graph

Using the Function

To use the function all we need to do is this…


…and we should get something like this


2 replies on “Colouring Nodes According to Centrality – R”

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s