Using r2d3 with Shiny

Overview

Integrating Shiny and D3 can be a powerful combination. Deriving insights from data is streamlined when users are able to modify a Shiny input, or click on a D3 visualization, and that action produces new results.

There are two ways that D3 visualizations can be integrated with Shiny. The difference has to do with the direction of the communication:

From Shiny to D3

From D3 to Shiny

Shiny to D3

When going from Shiny to D3, users make changes to Shiny inputs which result in changes to the D3 visualization. The r2d3 package provides two functions that enables this functionality:

First, we need to decide which attribute (.attr) is going to be passed to Shiny when the user clicks. Any existing attribute can be passed, such as the value of y or width, but because no current attribute contain the raw value of the data, a new made up attribute is added, we called it d. The d attribute is set to rerun the d variable.

Next, the on() function is used to capture an event inside the plot.The first argument is “click”, indicating that we want it to be activated when someone clicks on the plot. The second argument of on() is a function, this function will contain a call to the Shiny.setInputValue() JS function. The first argument of the Shiny JS function is the name that the Shiny app will be looking for. In this case, we will use bar_clicked. The second argument is the value that is returned to Shiny, and for that, we will use the d attribute created previously. The third argument, {priority: "event"}, is an option for input values that want to be treated less like values to be monitored, and more like events that are not to be missed.

The ui contains a text output named selected. Server-side, a reactive function, called output$selected() will used to capture the changes of the bar selection.

In the D3 script, we called Shiny.setInputValued() with an input named bar_clicked. This can now be used as if was an Shiny input in the app. In this case, the name to track will be: input$bar_clicked. The Shiny.setInputValued() JS function is recognized by the shiny package version 1.1 and above.

The output$selected() function uses renderText() to display the cosine of the bar that was clicked on. The call to input$bar_clicked is used inside renderText() to execute the cos() calculation.

The default value of input$bar_clicked will be NULL at the startup of the app. In this state you won’t want to perform any calculation (as it would result in an error) or display any output. Shiny’s req() function can be used to prevent errors in this case req() stops reactivity if the value of the variable passed as an argument is not valid, read more about this function in Shiny’s official site: Check for required values