0

そのため、データベースから取得した情報を繰り返し処理し、D3 チャートで動的にレンダリングする必要があります。必要な 2 つの情報は、回答のタイトルとその投票数です。私は現在、次のようにしています:

  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 に答える