哪个数据结构发送到d3.js脚本

Which datastructure to send to d3.js script?

本文关键字:d3 js 脚本 数据结构      更新时间:2023-09-26

所以我将需要迭代我从数据库中提取的一些信息,并在D3图表中动态渲染它。我需要的两个信息是答案的标题和票数。我现在是这样做的:

  def show
    @poll = Poll.find(params[:id])
    # Mappning answer titles with their votes 
    gon.poll = @poll.questions[0].answers.map{|answer| [answer.title, answer.votes]}

给出如下结果:

[["Probably not", 4],
 ["But you're saying there's a chance", 10],
 ["I just added this...", 7]]

并传递给这个脚本

$(document).ready(function() {
  var w = 500;
  var h = 420;
  var barPadding = 1;
  // var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
  //                 11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
  var dataset [gon.poll];
  // function drawSurvey(){
    var svg = d3.select('div.graph')
                .append("svg") 
                .attr("width", w)
                .attr("height",h);
                // .attr("class", "bar")
                // });
    svg.selectAll("rect")
       .data(dataset)
       // Each data point entered into enter() for processing
       .enter()
       .append("rect")
       .attr("x", function(d, i) {
          return i * (w / dataset.length);  //Bar width of 20 plus 1 for padding
      // tying of each bar as a function to length of set, never runs off screen
       })
       .attr("y", function(d){
          return h-d
       })
       // Less bars == more width
       .attr("width", w / dataset.length - barPadding)
       .attr("height", function(d){
        return d
       })
       .attr("fill", "teal");
  // }
});

我想知道这是否是处理数据的最有效的方法?我希望每个条都有其投票的高度,其"标题"在x轴上。什么好主意吗?

我将使用的数据结构将是一个对象数组:

[{title: "Probably not", votes: 4},
{title: "But you're saying there's a chance", votes: 10},
{title: "I just added this...", votes: 7}]

然后,在代码的后面:

.attr("y", function(d) {return d.votes;})

.attr("height", function(d) {return d.votes;})

对于标题,您可以使用d.title访问正确的值