Search code examples
rggplot2igraphgraph-visualizationggally

Color by degree in R using ggnet2


I've been trying to plot a graph using ggnet2. To do this I use the following code:

library(igraph)
lapply(c("sna", "intergraph", "GGally", "igraph", "network"), require, character.only=T)
data <- read.table('CA-CondMat.txt',sep="\t",header=TRUE)
g = graph.data.frame(data, directed = TRUE)
N = vcount(g)
E = ecount(g)
perc = 0.1
d.g = degree(g,mode='all')/N
new_nodes = sample.int(N,ceiling(perc*N),replace=FALSE,prob =d.g)
new_g = subgraph(g,new_nodes)
dg = degree(g,mode='all')
prob = dg/sum(dg)
png('example_plot2.png')
ggnet2(new_g, size = "degree", node.color = "steelblue", size.cut = 4,
                                          edge.size = 1, edge.color="grey" )
dev.off()

and I get a completely blue graph.

I'm using the package igraph.

What I want to plot is a graph with the nodes' color based on their degree like this one: enter image description here

Link to the file:
https://snap.stanford.edu/data/ca-CondMat.html

Edit:

Full example added


Solution

  • I appreciate a challenge, and graphs are always fun. I think this is what you want (I modified my original to use the file you provided later as I was working on it):

    In my code clr-degree is one half of the degree, as this file only has symmetric links and it looked rather boring without the black and green nodes.

    I also added library prefixes to all the calls so I could see what was being used from what network library (igraph, network, etc). There is a lot of overlap and inter-dependencies in these libraries.

    Note this code should map clr-degree to 0-1 to black, degree 2 to red, degree 3 to green, and >=4 to red:

    library(ggplot2)
    library(igraph)
    library(GGally)
    
    # the following libraries will be required too - used internally
    lapply(c("sna", "scales","intergraph", "network"),require, character.only=T)
    
    set.seed(1234)
    
    # data from  https://snap.stanford.edu/data/ca-CondMat.html
    data <- read.table('CA-CondMat.txt',sep="")
    
    g = igraph::graph.data.frame(data, directed = TRUE)
    N = vcount(g)
    E = ecount(g)
    d.g = igraph::degree(g,mode='all')/N
    
    # Use new smaller subgraph
    perc = 0.05
    new_nodes = sample.int(N,ceiling(perc*N),replace=FALSE,prob =d.g)
    new_g = igraph::subgraph(g,new_nodes)
    dg = igraph::degree(new_g,mode='all')
    
    dg <- dg/2  # for some reason there are only even degrees in this file - so we divide by 2
    
    clrvek = pmax(0,pmin(dg,4))
    clrnames = c("0"="lightgrey","1"="black", "2"="blue", "3"="green", "4"="red")
    
    #png('example_plot2.png')
    GGally::ggnet2(new_g, 
           color.legend="clr-degree",palette=clrnames,color=clrvek,
           size = "degree",
           edge.size = 1, edge.color="grey",
           legend.position = "bottom") + coord_equal()
    #dev.off()
    

    Yielding:

    enter image description here