networkD3:
D3 JavaScript Network Graphs from R

Fork me on

CRAN Version Dev-version: 0.4

Issues/suggestions

Christopher Gandrud, JJ Allaire, Kent Russell, & CJ Yetman

2017-03-18






About

This started as a port of Christopher Gandrud’s R package d3Network for creating D3 network graphs to the htmlwidgets framework. The htmlwidgets framework greatly simplifies the package’s syntax for exporting the graphs, improves integration with RStudio’s Viewer Pane, RMarkdown, and Shiny web apps. See below for examples.

It currently supports the following types of network graphs:

Install

networkD3 works very well with the most recent version of RStudio (>=v0.99, download). When you use this version of RStudio, graphs will appear in the Viewer Pane. Not only does this give you a handy way of seeing and tweaking your graphs, but you can also export the graphs to the clipboard or a PNG/JPEG/TIFF/etc. file.

The package can be downloaded from CRAN.

Usage

For a full set of examples for each of the functions see this page.

Note: You are probably used to R’s 1-based numbering (i.e. counting in R starts from 1). However, networkD3 plots are created using JavaScript, which is 0-based. So, your data links will need to start from 0. See this data set for example. You can also use igraph to build your graph data and then use the igraph_to_networkD3 function to convert this data to a suitable object for networkD3 plotting.

> simpleNetwork

For very basic force directed network graphics you can use simpleNetwork. For example:

# Load package
library(networkD3)

# Create fake data
src <- c("A", "A", "A", "A",
        "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",
            "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)

# Plot
simpleNetwork(networkData)
ABCDEFGHIJ

> forceNetwork

Use forceNetwork to have more control over the appearance of the forced directed network and to plot more complicated networks. Here is an example:

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = 0.8)
MyrielNapoleonMlle.BaptistineMme.MagloireCountessdeLoGeborandChamptercierCravatteCountOldManLabarreValjeanMargueriteMme.deRIsabeauGervaisTholomyesListolierFameuilBlachevilleFavouriteDahliaZephineFantineMme.ThenardierThenardierCosetteJavertFaucheleventBamataboisPerpetueSimpliceScaufflaireWoman1JudgeChampmathieuBrevetChenildieuCochepaillePontmercyBoulatruelleEponineAnzelmaWoman2MotherInnocentGribierJondretteMme.BurgonGavrocheGillenormandMagnonMlle.GillenormandMme.PontmercyMlle.VauboisLt.GillenormandMariusBaronessTMabeufEnjolrasCombeferreProuvaireFeuillyCourfeyracBahorelBossuetJolyGrantaireMotherPlutarchGueulemerBabetClaquesousMontparnasseToussaintChild1Child2BrujonMme.Hucheloup

From version 0.1.3 you can also allow scroll-wheel zooming by setting zoom = TRUE.

> sankeyNetwork

You can also create Sankey diagrams with sankeyNetwork. Here is an example using downloaded JSON data:

# Load energy projection data
# Load energy projection data
URL <- paste0(
        "https://cdn.rawgit.com/christophergandrud/networkD3/",
        "master/JSONdata/energy.json")
Energy <- jsonlite::fromJSON(URL)
# Plot
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             units = "TWh", fontSize = 12, nodeWidth = 30)
Nuclear → Thermal generation
840 TWh
Thermal generation → Losses
787 TWh
Oil → Liquid
612 TWh
Thermal generation → Electricity grid
526 TWh
Oil imports → Oil
504 TWh
Solid → Thermal generation
400 TWh
Electricity grid → Industry
342 TWh
Wind → Electricity grid
289 TWh
Bio-conversion → Solid
280 TWh
Liquid → International aviation
206 TWh
Pumped heat → Heating and cooling - homes
193 TWh
UK land based bioenergy → Bio-conversion
182 TWh
Gas → Thermal generation
152 TWh
Liquid → Road transport
136 TWh
Liquid → International shipping
129 TWh
Agricultural 'waste' → Bio-conversion
125 TWh
Ngas → Gas
123 TWh
Liquid → Industry
121 TWh
Electricity grid → Heating and cooling - homes
114 TWh
Oil reserves → Oil
108 TWh
Electricity grid → Over generation / exports
104 TWh
Electricity grid → Lighting & appliances - homes
93 TWh
Electricity grid → Lighting & appliances - commercial
90 TWh
Gas reserves → Ngas
82 TWh
Bio-conversion → Gas
81 TWh
Thermal generation → District heating
79 TWh
Other waste → Bio-conversion
78 TWh
Coal → Solid
76 TWh
Pumped heat → Heating and cooling - commercial
71 TWh
Coal reserves → Coal
64 TWh
Solar PV → Electricity grid
60 TWh
Solar → Solar PV
60 TWh
Electricity grid → Losses
57 TWh
Other waste → Solid
57 TWh
Gas → Industry
49 TWh
Solid → Industry
46 TWh
District heating → Heating and cooling - homes
46 TWh
Electricity grid → Heating and cooling - commercial
41 TWh
Gas imports → Ngas
41 TWh
Electricity grid → Road transport
38 TWh
Biofuel imports → Liquid
35 TWh
Biomass imports → Solid
35 TWh
Liquid → National navigation
33 TWh
Electricity grid → H2 conversion
27 TWh
Bio-conversion → Losses
27 TWh
District heating → Heating and cooling - commercial
23 TWh
H2 conversion → H2
21 TWh
H2 → Road transport
21 TWh
Solar Thermal → Heating and cooling - homes
19 TWh
Solar → Solar Thermal
19 TWh
Wave → Electricity grid
19 TWh
Liquid → Domestic aviation
14 TWh
Coal imports → Coal
12 TWh
District heating → Industry
11 TWh
Tidal → Electricity grid
9 TWh
Electricity grid → Rail transport
8 TWh
Geothermal → Electricity grid
7 TWh
Hydro → Electricity grid
7 TWh
H2 conversion → Losses
6 TWh
Liquid → Rail transport
4 TWh
Electricity grid → Agriculture
4 TWh
Marine algae → Bio-conversion
4 TWh
Liquid → Agriculture
4 TWh
Gas → Agriculture
2 TWh
Gas → Losses
1 TWh
Solid → Agriculture
1 TWh
Bio-conversion → Liquid
1 TWh
Gas → Heating and cooling - commercial
0 TWh
Agricultural 'waste'
125 TWh
Agricultural 'waste'
Bio-conversion
389 TWh
Bio-conversion
Liquid
648 TWh
Liquid
Losses
878 TWh
Losses
Solid
447 TWh
Solid
Gas
204 TWh
Gas
Biofuel imports
35 TWh
Biofuel imports
Biomass imports
35 TWh
Biomass imports
Coal imports
12 TWh
Coal imports
Coal
76 TWh
Coal
Coal reserves
64 TWh
Coal reserves
District heating
79 TWh
District heating
Industry
569 TWh
Industry
Heating and cooling - commercial
134 TWh
Heating and cooling - commercial
Heating and cooling - homes
372 TWh
Heating and cooling - homes
Electricity grid
919 TWh
Electricity grid
Over generation / exports
104 TWh
Over generation / exports
H2 conversion
27 TWh
H2 conversion
Road transport
195 TWh
Road transport
Agriculture
11 TWh
Agriculture
Rail transport
12 TWh
Rail transport
Lighting & appliances - commercial
90 TWh
Lighting & appliances - commercial
Lighting & appliances - homes
93 TWh
Lighting & appliances - homes
Gas imports
41 TWh
Gas imports
Ngas
123 TWh
Ngas
Gas reserves
82 TWh
Gas reserves
Thermal generation
1,392 TWh
Thermal generation
Geothermal
7 TWh
Geothermal
H2
21 TWh
H2
Hydro
7 TWh
Hydro
International shipping
129 TWh
International shipping
Domestic aviation
14 TWh
Domestic aviation
International aviation
206 TWh
International aviation
National navigation
33 TWh
National navigation
Marine algae
4 TWh
Marine algae
Nuclear
840 TWh
Nuclear
Oil imports
504 TWh
Oil imports
Oil
612 TWh
Oil
Oil reserves
108 TWh
Oil reserves
Other waste
134 TWh
Other waste
Pumped heat
264 TWh
Pumped heat
Solar PV
60 TWh
Solar PV
Solar Thermal
19 TWh
Solar Thermal
Solar
79 TWh
Solar
Tidal
9 TWh
Tidal
UK land based bioenergy
182 TWh
UK land based bioenergy
Wave
19 TWh
Wave
Wind
289 TWh
Wind

> radialNetwork

From version 0.2, tree diagrams can be created using radialNetwork or diagonalNetwork.

URL <- paste0(
        "https://cdn.rawgit.com/christophergandrud/networkD3/",
        "master/JSONdata//flare.json")

## Convert to list format
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)

# Use subset of data for more readable diagram
Flare$children = Flare$children[1:3]

radialNetwork(List = Flare, fontSize = 10, opacity = 0.9)
flareanalyticsanimatedataclustergraphoptimizationEasingFunctionSequenceinterpolateISchedulableParallelPauseSchedulerSequenceTransitionTransitionerTransitionEventTweenconvertersDataFieldDataSchemaDataSetDataSourceDataTableDataUtilAgglomerativeClusterCommunityStructureHierarchicalClusterMergeEdgeBetweennessCentralityLinkDistanceMaxFlowMinCutShortestPathsSpanningTreeAspectRatioBankerArrayInterpolatorColorInterpolatorDateInterpolatorInterpolatorMatrixInterpolatorNumberInterpolatorObjectInterpolatorPointInterpolatorRectangleInterpolatorConvertersDelimitedTextConverterGraphMLConverterIDataConverterJSONConverter
diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9)
flareanalyticsanimatedataclustergraphoptimizationEasingFunctionSequenceinterpolateISchedulableParallelPauseSchedulerSequenceTransitionTransitionerTransitionEventTweenconvertersDataFieldDataSchemaDataSetDataSourceDataTableDataUtilAgglomerativeClusterCommunityStructureHierarchicalClusterMergeEdgeBetweennessCentralityLinkDistanceMaxFlowMinCutShortestPathsSpanningTreeAspectRatioBankerArrayInterpolatorColorInterpolatorDateInterpolatorInterpolatorMatrixInterpolatorNumberInterpolatorObjectInterpolatorPointInterpolatorRectangleInterpolatorConvertersDelimitedTextConverterGraphMLConverterIDataConverterJSONConverter

> dendroNetwork

From version 0.2, it is also possible to create dendrograms using dendroNetwork.

hc <- hclust(dist(USArrests), "ave")

dendroNetwork(hc, height = 600)
FloridaNorth CarolinaCaliforniaHawaiiMarylandAlaskaWashingtonRhode IslandMissouriGeorgiaIdahoArizonaNew MexicoDelawareMississippiSouth CarolinaOregonMassachusettsNew JerseyArkansasTennesseeColoradoTexasNebraskaOhioUtahWest VirginiaAlabamaLouisianaIllinoisNew YorkMichiganNevadaWyomingKentuckyMontanaIndianaKansasConnecticutPennsylvaniaMaineSouth DakotaNorth DakotaVermontMinnesotaOklahomaVirginiaWisconsinIowaNew Hampshire

Interacting with igraph

You can use igraph to create network graph data that can be plotted with networkD3. The igraph_to_networkD3 function converts igraph graphs to lists that work well with networkD3. For example:

# Load igraph
library(igraph)

# Use igraph to make the graph and find membership
karate <- make_graph("Zachary")
wc <- cluster_walktrap(karate)
members <- membership(wc)

# Convert to object suitable for networkD3
karate_d3 <- igraph_to_networkD3(karate, group = members)

# Create force directed network plot
forceNetwork(Links = karate_d3$links, Nodes = karate_d3$nodes, 
             Source = 'source', Target = 'target', 
             NodeID = 'name', Group = 'group')
12345678910111213141516171819202122232425262728293031323334

Output

Saving to an external stand alone HTML file

Use saveNetwork to save a network to a stand alone HTML file:

library(magrittr)

simpleNetwork(networkData) %>%
saveNetwork(file = 'Net1.html')

Including in an RMarkdown file

It is simple to include a networkD3 graphic in an RMarkdown file. Simply place the code to create the graph in a code chunk the same way you would any other plot. Checkout this simple example.

Including in Shiny web apps

You can also easily include networkD3 graphs in Shiny web apps.

In the server.R file create the graph by placing the function inside of render*Network, where the * is either Simple, Force, or Sankey depending on the graph type. For example:

output$force <- renderForceNetwork({
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = input$opacity)
})

In the shinyUI part of your app.R file (for single-file Shiny apps) include *NetworkOutput (with * as before, but starting with a lowercase letter). The argument placed in this function should be the element specified with output, e.g.:

forceNetworkOutput("force")

You can run a simple example with the following code:

shiny::runGitHub('christophergandrud/networkD3-shiny-example')

Full source code for this example can be found here.

Saving as static PNG image

You can use RStudio to save static images of networkD3 plots as PNG files. Simply create your plot as usual in RStudio. The output should appear in the Viewer pane. Then click Export > Save as Image…. A new window will appear. You can use this window to manipulate the plot, resize it, and save the result as a PNG file.

RStudio-save-plot-as-image






BerlinBadge

Christopher Gandrud

networkD3 is covered under the GPL-3 license.

This site is covered under a CC By-NC-SA 4.0 License.