Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use R data.frame object in d3.js using r2d3

Tags:

r

d3.js

r2d3

I'm trying to understand how an R data frame is passed to a d3.js script using the package r2d3. An extension of the r2d3 bar chart example to access variables in data.frame object would be helpful.

R code:

library(r2d3)
data <- data.frame(nums = c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20))
r2d3(data, script = "test.js")

js code:

var barHeight = Math.floor(height / data.length);

svg.selectAll('rect')
  .data(data.nums)
  .enter().append('rect')
    .attr('width', function(d) { return d * width; })
    .attr('height', barHeight)
    .attr('y', function(d, i) { return i * barHeight; })
    .attr('fill', 'steelblue');

Error:

Error: svg.selectAll(...).data(...).enter is not a function in (test.js#5:4)
TypeError: svg.selectAll(...).data(...).enter is not a function
like image 978
ssp3nc3r Avatar asked Mar 14 '19 16:03

ssp3nc3r


1 Answers

This error occurs because data.nums is undefined.

Your data variable is not an object containing an array as follows:

var data = {
      nums: [0.3,0.6,0.8,0.95,0.40,0.20]
    }

But, rather an array containing objects:

var data = [
  {nums:0.3},
  {nums:0.6},
  {nums:0.8},
  {nums:0.95},
  {nums:0.40},
  {nums:0.2}
]

To keep you r side code, we just need to pass the data array itself to selection.data() and access the nums property of each datum:

var barHeight = Math.floor(height / data.length);

svg.selectAll('rect')
  .data(data)
  .enter().append('rect')
    .attr('width', function(d) { return d.nums * width; })
    .attr('height', barHeight)
    .attr('y', function(d, i) { return i * barHeight; })
    .attr('fill', 'steelblue');
like image 111
Andrew Reid Avatar answered Nov 07 '22 17:11

Andrew Reid