Integrating D3.js into R Shiny

In the past I’ve built apps with R Shiny, and I’ve also developed a few data visualisations with d3.js. Given that R Shiny is an R based Back End Server that renders a Front End in Java Script, it seemed like it would be possible to integrate a d3.js visualisation into an R Shiny App. After some quick research, it turns out that it is possible, this blog explains how to do it, and here is an example (please note this is hosted on Shiny.io and sometimes runs out of free hours each month)

I’m assuming a basic understanding of both R Shiny and d3.js. The process works around sending custom messages between the back end and the front end. Here’s how:

In your Shiny server file, create the JSON dataset that you wish to visualize. Then in the server file use the command:

session$sendCustomMessage(type="jsondata",var_json)

This sends a custom message across to the front end. In this case var_json would be the R object containing the JSON data. The type can be any label you like. You just reference it in the d3.js script to pick it up.

Next in the Shiny app area, create a folder labelled “www”. In this folder create a “.css” styling file for your d3 visualisation, and a “.js” javascript file to contain the d3.js code. At the top of the “.js” file, add message handling function like this:Shiny.addCustomMessageHandler("jsondata",function(message){var json_data = message;

This searches for the custom message of the type “jsondata”. Then it takes the contents of the message, and assigns them to a java script variable, in this case json_data. Then place the d3.js code here referencing the json_data variable for the data, and close off the function. Make sure the div containing the visualisation has an ID to reference. Next alter the “.css” file to style your visualisation.

Finally in the Shiny UI file,

Use the tag$head to read in your “.css” filetags$head(tags$link(rel = "stylesheet", type = "text/css", href = "style.css"))

Use tags$script to load the d3 librarytags$script(src="https://d3js.org/d3.v3.min.js")

Use it again to read in the “.js” script containing the d3 visualisationtags$script(src="d3script.js")

Then finally use the tags$div to render the div in position in the Shiny Apptags$div(id="div_reference")

And that’s it.

I’ve created an interactive discography app around the SpotifyAPI package I previously built. The Shiny App takes an input artist from the user. Then hits the Spotify API to find all the albums and tracks for that artist. Then renders them in a d3.js tree diagram with the ability to play a sample from each track. The code is on my github.

For lots of other useful Shiny tricks check out this useful book