无法将文本附加到d3.js强制模拟圈

时间:2017-10-19 11:11:37

标签: javascript d3.js

(function(){

//width and height
var width = 800,
    height = 500;

//appending svg to the body and defining the canvas
var svg = d3.select("#chart")
            .append("svg")
            .attr("height", height)
            .attr("width", width)
            .append("g")
            .attr("transform","translate(0,0)");
d3.queue()
  .defer(d3.csv, "result1.csv")
  .await(ready);

function ready(error, datapoints){

    if(error){
        console.log(error);
    }else{

      var color = d3.scaleLinear(datapoints)
                  .domain([1, 77])
                  .range(["#ffffff","#DD4B39"]);

      var radiusScale = d3.scaleSqrt().domain([1, 10]).range([2,80]);

      var simulation = d3.forceSimulation()
                       .force("x", d3.forceX(width/2).strength(0.05))
                       .force("y", d3.forceY(height/2).strength(0.05))
                       .force("center", d3.forceCenter().x(width * .5).y(height * .5))
                       .force("collide", d3.forceCollide(function(d){
                          return radiusScale(d.rad);
                       }));

      var nodes = svg.append("g")
           .attr("class", "nodes")
           .selectAll("circle")
           .data(datapoints)
           .enter()
           .append("g")
           .attr("transform", function(d, i) {
             return "translate(" + width/12 + "," + height/12 + ")";
           });

      nodes.append("circle")
            .attr("r", function(d){
                return radiusScale(d.rad);
            })
            .attr("class","bubble")
            .attr("stroke","#5e0000")
            .attr("fill","red")
            .attr("fill", function(d) { 
                    return color(d.rad);
                });

              simulation.nodes(datapoints)
                        .on('tick',ticked);

              function ticked(){
                nodes
                  .attr("cx",function(d){return d.x})
                  .attr("cy",function(d){return d.y});
              }

    nodes.append("text")
         .attr("class","system")
         .attr("text-anchor", "middle")
         .text(function(d) {
           return d.rad;
          });
    }
}
})();

以上是我的剧本。我试图在文本中添加d3.js强制模拟的圆圈。我尝试了几种方法,但不能将文字附加到圆圈。请给我一个解决方案。当我将模拟设置为气泡类时 var nodes = d3.selectAll(" .bubble"); ,然后它只模拟圆圈。但文字是看不见的。帮忙。

0 个答案:

没有答案