Categories

# 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 `erdos.renyi.game( )` function.

```my_g <- erdos.renyi.game(100,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
plot(
g,
layout=layout.fruchterman.reingold,
vertex.label=NA,
vertex.size=4,
vertex.frame.color="black",
edge.width=1
)
}
```

## Using the Function

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

```color.cent.graph(my_g)
```

…and we should get something like this ## 2 replies on “Colouring Nodes According to Centrality – R”

[…] Here is a more up-to-date entry […]

[…] Colouring Nodes According to Centrality – R. […]