stats_noob
stats_noob

Reputation: 5907

Manipulating "networkD3" objects in R

I am using the networkD3 library in R to create a relationship graph for my data:

library(igraph)
library(dplyr)
library(networkD3)

#create file from which to sample from
x5 <- sample(1:1000000000, 2000, replace=T)
#convert to data frame
x5 = as.data.frame(x5)

#create first file (take a random sample from the created file)
a = sample_n(x5, 1000)
#create second file (take a random sample from the created file)
b = sample_n(x5, 1000)

#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")

#convert to factors
c$a = as.factor(c$a)
c$b = as.factor(c$b)


#plot graph (with networkD3)
c = data.frame(c)
simpleNetwork(c, fontSize= 20, zoom = T)

When I make this graph, I find that the output is not very easy to view and manipulate.

I am trying to use the forcegraph layout, but I am having difficulty using it:

forceNetwork(Links = c$b, Nodes = c$a,
            Source = "source", Target = "target",
            Value = "value", NodeID = "c$a",
            opacity = 0.8)

Could someone please tell me what I am doing wrong?

Upvotes: 1

Views: 152

Answers (1)

Mako
Mako

Reputation: 96

To my understanding is the data format slightly different for forceNetwork compared to simpleNetwork.

The Links argument needs a table holding the indices of the nodes stored in the Node table (2 columns: 'from' - 'to', or as in the example 'source' - 'target'). Be aware that the index should start with 0 and not 1. A 3rd column of 'Links' should be the edge width.

The Nodes argument needs a table with the 1) the name and 2) the group.

The additional arguments you are using in your example are column names of corresponding columns in the table you use in 'Links' and 'Nodes'. For instance when you use NodeID = "c$a" that means that your node table has a column named 'c$a'.

Have a look at the help page :?forceNetwork they describing the arguments much better than I can, but also scroll down to the examples and check the shape of their example data (MisLinks and MisNodes).

Maybe this litte code can give you an orientation (continues with your 'c' object):

c$a = as.character(c$a)
c$b = as.character(c$b)

Nodes_IDs <- data.frame(name=sort(unique(c(c$a, c$b))))
Nodes_IDs$gr <- 1

# JavaScript need zero-indexed IDs.
c$a <- match(c$a, Nodes_IDs[,1]) -1
c$b <- match(c$b, Nodes_IDs[,1]) -1
c$width <- .5

forceNetwork(Links = c, Nodes = Nodes_IDs,
             Source = "a", Target = "b",
             Value = "width", NodeID = "name",
             Group = "gr",
             opacity = 0.8)

Upvotes: 3

Related Questions