【问题标题】:Use R data.frame object in d3.js using r2d3使用 r2d3 在 d3.js 中使用 R data.frame 对象
【发布时间】:2019-08-05 16:15:43
【问题描述】:

我试图了解如何使用包r2d3 将 R 数据帧传递给 d3.js 脚本。 r2d3 条形图示例的扩展以访问 data.frame 对象中的变量会很有帮助。

R 代码:

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代码:

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: svg.selectAll(...).data(...).enter is not a function in (test.js#5:4)
TypeError: svg.selectAll(...).data(...).enter is not a function

【问题讨论】:

    标签: r d3.js r2d3


    【解决方案1】:

    出现此错误是因为 data.nums 未定义。

    您的data 变量不是包含如下数组的对象:

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

    但是,而是一个包含对象的数组:

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

    为了让您保留r 侧代码,我们只需将数据数组本身传递给selection.data() 并访问每个数据的nums 属性:

    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');
    

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 2017-01-15
      • 1970-01-01
      • 2021-05-23
      • 2021-12-27
      • 2017-04-16
      • 2022-01-16
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多