Skip to main content

Quick and Simple D3 Network Graphs from R

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 bare-bones simple function–called d3SimpleNetwork for turning an R data frame into a D3 network graph.


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.


Here's a simple example. First load d3SimpleNetwork:

# Load packages to download d3SimpleNetwork

# Download d3SimpleNetwork

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.

Update 12 June 2013: The original d3SimpleNetwork command discussed here doesn't work easily with slidify. I have created a new d3Network R package that does work well with slidify (and other knitr-created HTML slideshows). Use its d3Network command and set the argument iframe = TRUE.


nxskok said…
It works, and is very pretty!

I saved the output to an html file, and it displayed with Firefox. I like how it spaces out the nodes. Next, I am going to try it on a more complicated graph.
Unknown said…
Great to hear you liked it.

I'm thinking of adding a small tweak that allows you to change the node spacing.
G$ said…
This is pretty cool. I took my package dependencies and piped it to the d3 network graph so I could see what the dependency graph looks like. Interesting to see how the packages build on each other


package <- grep("^package:", search(), value = TRUE)
keep <- sapply(package, function(x) x == "package:base" ||
!is.null(attr(as.environment(x), "path")))
package <- sub("^package:", "", package[keep])

x = foreach(p=iter(package)) %do% {dependsOnPkgs(p, recursive=FALSE)}
names(x) = package

# parse them into Source and Targets
Source = foreach(i=1:length(x), .combine='c') %do% {rep(names(x[i]),length(x[[i]]))}
Target = (foreach(i=1:length(x), .combine='c') %do%{x[[i]]})
NetworkData <- data.frame(Source, Target)

# Load packages to download d3SimpleNetwork

# Download d3SimpleNetwork
d3SimpleNetwork(NetworkData, height = 800, width = 1280, file='myPackages.html')
Unknown said…
@G$ Really nice!

If your interested, take a look at the new package version of d3Network. It allows you to change things like the font size and link distances:
Fr. said…
I have posted an example at the end of this blog post, which shows another plot function for networks, using ggplot2.

Popular posts from this blog

Dropbox & R Data

I'm always looking for ways to download data from the internet into R. Though I prefer to host and access plain-text data sets (CSV is my personal favourite) from GitHub (see my short paper on the topic) sometimes it's convenient to get data stored on Dropbox . There has been a change in the way Dropbox URLs work and I just added some functionality to the repmis R package. So I though that I'ld write a quick post on how to directly download data from Dropbox into R. The download method is different depending on whether or not your plain-text data is in a Dropbox Public folder or not. Dropbox Public Folder Dropbox is trying to do away with its public folders. New users need to actively create a Public folder. Regardless, sometimes you may want to download data from one. It used to be that files in Public folders were accessible through non-secure (http) URLs. It's easy to download these into R, just use the read.table command, where the URL is the file name

Slide: one function for lag/lead variables in data frames, including time-series cross-sectional data

I often want to quickly create a lag or lead variable in an R data frame. Sometimes I also want to create the lag or lead variable for different groups in a data frame, for example, if I want to lag GDP for each country in a data frame. I've found the various R methods for doing this hard to remember and usually need to look at old blog posts . Any time we find ourselves using the same series of codes over and over, it's probably time to put them into a function. So, I added a new command– slide –to the DataCombine R package (v0.1.5). Building on the shift function TszKin Julian posted on his blog , slide allows you to slide a variable up by any time unit to create a lead or down to create a lag. It returns the lag/lead variable to a new column in your data frame. It works with both data that has one observed unit and with time-series cross-sectional data. Note: your data needs to be in ascending time order with equally spaced time increments. For example 1995, 1996

A Link Between topicmodels LDA and LDAvis

Carson Sievert and Kenny Shirley have put together the really nice LDAvis R package. It provides a Shiny-based interactive interface for exploring the output from Latent Dirichlet Allocation topic models. If you've never used it, I highly recommend checking out their XKCD example (this paper also has some nice background). LDAvis doesn't fit topic models, it just visualises the output. As such it is agnostic about what package you use to fit your LDA topic model. They have a useful example of how to use output from the lda package. I wanted to use LDAvis with output from the topicmodels package. It works really nicely with texts preprocessed using the tm package. The trick is extracting the information LDAvis requires from the model and placing it into a specifically structured JSON formatted object. To make the conversion from topicmodels output to LDAvis JSON input easier, I created a linking function called topicmodels_json_ldavis . The full function is below. To