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)
In your Shiny server file, create the JSON dataset that you wish to visualize. Then in the server file use the command:
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.
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” file
tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "style.css"))
Use tags$script to load the d3 library
Use it again to read in the “.js” script containing the d3 visualisation
Then finally use the tags$div to render the div in position in the Shiny App
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