Quick and Simple D3 Network Graphs from R

[This article was first published on Christopher Gandrud (간드루드 크리스토파), and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Sometimes I just want to quickly make a simple D3 JavaScript directed network graph with data in R. Because D3 network graphs can be manipulated in the browser–i.e. nodes can be moved around and highlighted–they're really nice for data exploration. They're also really nice in HTML presentations. So I put together a really bare-bones simple function–called d3SimpleNetwork for turning an R data frame into a D3 network graph.

Arguments

By bare-bones I mean other than the arguments indicating the Data data frame, as well as the Source and Target variables it only has three arguments: height, width, and file.

The data frame you use should have two columns that contain the source and target variables. Here's an example using fake data:

Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
NetworkData <- data.frame(Source, Target)

The height and width arguments obviously set the graph's frame height and width. You can tell file the file name to output the graph to. This will create a standalone webpage. If you leave file as NULL, then the graph will be printed to the console. This can be useful if you are creating a document using knitr Markdown or (similarly) slidify. Just set the code chunk results='asis and the graph will be rendered in the document.

Example

Here's a simple example. First load d3SimpleNetwork:

# Load packages to download d3SimpleNetwork
library(digest)
library(devtools)

# Download d3SimpleNetwork
source_gist("5734624")

Now just run the function with the example NetworkData from before:

d3SimpleNetwork(NetworkData, height = 300, width = 700)

Click here for the fully manipulable version. If you click on individual nodes they will change colour and become easier to see. In the future I might add more customisability, but I kind of like the function's current simplicity.

To leave a comment for the author, please follow the link and comment on their blog: Christopher Gandrud (간드루드 크리스토파).

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)