D3 in R

RStudio recently launched R2D3, giving R users the ability to render D3.js code in RStudio. For those in the data visualization field, this is a really exciting development. Now we can render D3 code in RMarkdown, R script, or Shiny. We can also pass R objects (i.e. dataframes, datatables, etc.) to D3 visualizations.

Secondly, we can wrap r2d3 functions and include them in packages! As an example, I've taken Simon's ideal point estimates D3 code, rewrote it so that it would work in r2d3, wrapped the result up into a function called d3_rollcall_idealpoints() and uploaded it to the ussc R package.

I'll walk you through the steps to run the function. Feel free to check out the r2d3 website if you want to learn more about D3 in R. NOTE: r2d3requires the daily build of RStudio.

knitr::opts_chunk$set(echo = TRUE, warnings=FALSE, message=FALSE)
library(r2d3)
library(here)
library(ussc)
#set wd or open the file directly. 
#load data
house_estimates <- read.csv(here("h_estimates.csv"))
head(house_estimates)

115th House of Representatives Ideal Point Estimates

#Run d3_rollcall_idealpoints for House of Rep data
#You *must* define the data frame -- we did that above, reading the csv file to house_estimates and defined the data below in the function itself. This is the beauty of r2d3 -- any data frame or R object will work if the variables match the javascript.
# Note: you can  set the height and width of the visualization inside the function or add it to the R chunk.
d3_rollcall_idealpoints(data=house_estimates, height=20)
#load data
senate_estimates <- read.csv(here("s_estimates.csv"))

115th Senate Ideal Point Estimates

#run d3_rollcall_idealpoints for Senate data
d3_rollcall_idealpoints(data=senate_estimates)

There you have it! Pretty simple, huh? Interactive D3.js visualizations without the hassle.



USStudiesCentre/ussc documentation built on Sept. 2, 2020, 2:51 p.m.