要发送到d3.js脚本的数据结构是什么?

时间:2013-06-10 22:22:23

标签: javascript ruby-on-rails data-structures d3.js

所以我需要迭代我从数据库中提取的一些信息并在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轴上有'标题'。任何想法?

1 个答案:

答案 0 :(得分:0)

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

[{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来访问正确的值。