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.

#load data
house_estimates <- read.csv(here("h_estimates.csv"))
head(house_estimates)
##   state icpsrState cd icpsrLegis party partyCode missingVotes idealPoint
## 1    NJ         12 12      21538     D       100            3  -2.673088
## 2    IL         21  9      29911     D       100            7  -2.213713
## 3    CA         71 11      21504     D       100            2  -2.206819
## 4    WA         73  7      21726     D       100            1  -1.962753
## 5    MS         46  2      29368     D       100            6  -1.928029
## 6    CA         71 13      29778     D       100            8  -1.891819
##          lo        up                label indx
## 1 -3.409719 -1.826614     WATSON (D NJ-12)    1
## 2 -3.236600 -1.331519  SCHAKOWSKY (D IL-9)    2
## 3 -2.826341 -1.651352 DESAULNIER (D CA-11)    3
## 4 -2.783893 -1.347681     JAYAPAL (D WA-7)    4
## 5 -2.412148 -1.319295    THOMPSON (D MS-2)    5
## 6 -2.482723 -1.271432        LEE (D CA-13)    6
  • Note: this code will really only work with Simon’s ideal points data as the defined variables in the D3 code are the same as this csv file. I would like to make a generic ideal points function in the future but this may be a while off.

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.