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
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With