0

因此,我将需要遍历从数据库中提取的一些信息,并将其动态呈现在 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 轴上。有任何想法吗?

4

1 回答 1

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

于 2013-06-12T21:03:51.227 回答