If you want to create an interactive visualization using R/Shiny and d3.js, check out the example below for a step-by-step guide along with code snippets.
Note from December 2018: Take into account MrGrumble's comment about changes in events when using d3 v5.
How to Reproduce:
To replicate this project, simply clone the repository from here.
Preview:
Apologies for the low quality of the gif, but you can still get an idea from it: https://i.sstatic.net/lUgeT.gif
Explanation:
The implementation involves combining d3.js, Shiny, and R. A custom shiny function called renderDragableChart()
is utilized to allow customization of circle colors and sizes. Check out the details in DragableFunctions.R
.
R-to-d3.js Interaction:
Initially, the data points' locations are set in R as demonstrated in server.R:
df <- data.frame(x = seq(20,150, length.out = 10) + rnorm(10)*8,
y = seq(20,150, length.out = 10) + rnorm(10)*8)
df$y[1] = df$y[1] + 80
The graphics rendering is managed through d3.js, including features like draggable points and updating changes back to R via
Shiny.onInputChange("JsData", coord);
.
The Code Structure:
ui.R:
This contains a customized shiny function called DragableChartOutput()
, defined in DragableFunctions.R
. Here's how it looks:
library(shiny)
shinyUI( bootstrapPage(
fluidRow(
column(width = 3,
DragableChartOutput("mychart")
),
column(width = 9,
verbatimTextOutput("regression")
)
)
))
server.R:
In addition to basic shiny functionality, there's a special function named renderDragableChart()
. Here's a snippet from the server script:
library(shiny)
options(digits=2)
df <- data.frame(x = seq(20,150, length.out = 10) + rnorm(10)*8,
y = seq(20,150, length.out = 10) + rnorm(10)*8)
df$y[1] = df$y[1] + 80
...
The specific functions are stored in DragableFunctions.R
for modularity. While using library(htmlwidgets)
could simplify the process, opting for the detailed approach helps in understanding the nuances better.
library(shiny)
...remaining code...
To delve deeper into the dynamic behavior powered by d3.js, refer to ChartRendering.js
. It showcases the circle generation and drag functionalities, ensuring real-time updates to R upon dragging completion.
var col = "orange";
...d3.js code snippet...