D3 Library — How To Access Data from JSON in this example

前端 未结 3 927
执笔经年
执笔经年 2021-01-01 04:36

I didn\'t explain the issue properly in the title... Sorry.

I\'m following the D3 Tag Cloud Simple example https://github.com/jasondavies/d3-cloud/blob/master/exampl

3条回答
  •  借酒劲吻你
    2021-01-01 04:50

    I suggest you should use the built-in import function for json instead of php. I think that the problem you have is that the reading of the data is asynchronous, so words is not filled before using it in clouds.

    The principle behind d3.json() is to do everything in this function, which will be executed when the json is loaded:

    var data; // a global
    d3.json("path/to/file.json", function(error, json) {
      if (error) return console.warn(error);
      data = json;
      visualizeit();
    });
    

    EDIT

    Here is an example of the code that should work, I just added the d3 cloud example inside the json function.

    d3.json("../../../assets/json/tweetTags.json", function(error, json) {
      if (error) return console.warn(error);
    
      var fill = d3.scale.category20();
    
      d3.layout.cloud().size([300, 300])    
          .words([  // To be replaced with data
            "Hello", "world", "normally", "you", "want", "more", "words",
            "than", "this"].map(function(d) {
                return {text: d, size: 10 + Math.random() * 90};
           }))
          .rotate(function() { return ~~(Math.random() * 2) * 90; })
          .font("Impact")
          .fontSize(function(d) { return d.size; })
          .on("end", draw)
          .start();
    
      function draw(words) {
          d3.select("body").append("svg")
              .attr("width", 300).attr("height", 300)
              .append("g").attr("transform", "translate(150,150)")
              .selectAll("text").data(words)
              .enter().append("text")
              .style("font-size", function(d) { return d.size + "px"; })
              .style("font-family", "Impact")
              .style("fill", function(d, i) { return fill(i); })
              .attr("text-anchor", "middle")
              .attr("transform", function(d) {
                  return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
              })
              .text(function(d) { return d.text; });
          }
    })
    

    Then, when this version works you can just replace the .words() by:

    .words(json.map(function(d) {
      return {text: d.word, size: d.sentiment * 40, tweet: d.tweet};
    }))
    

提交回复
热议问题