D3向Node SVG添加文本

时间:2017-08-29 09:25:40

标签: d3.js svg

我正在尝试使用以下代码添加标签,但仍然没有运气,似乎我的标签写在页面顶部而不是节点本身。我认为这是SVG的一个约束性问题。

我尝试添加标题但我无法显示它。

<!-- INITAL SETTINGS ------------------------------------------------------------------------------->
<!-------------------------------------------------------------------------------------------------->
<!DOCTYPE html>
<meta charset="utf-8">
<style>
    .links line {
        stroke: #999;
        stroke-opacity: 0.5;
    }

    .nodes circle {
        stroke: #fff;
        stroke-width: 1.2px;
    }
</style>
<!-- the SVG viewport will be 1100px by 900px -->
<svg width="1100" height="900" viewbox="0 0 1100 900">
    <text> </text>
    <!-- SVG content drawn onto the SVG canvas -->
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>


<script>
// DATA DEFINITIONS NODES & LINKS ------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
    var graph = {
        "nodes": [
                    { "id": "xxx1", "group": 3 },
                    { "id": "xxx2", "group": 1 },
                    { "id": "xxx3", "group": 1 }

        ],
        "links": [
                    { "source": "xxx1", "target": "xxx2", "value": 42 },
                    { "source": "xxx2", "target": "xxx3", "value": 6 },
                    { "source": "xxx1", "target": "xxx3", "value": 13 }
        ]
    };

// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// D3 CODE 
// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
    // create the construct/canvas for drawing
    var svg = d3.select("svg")
        //set width/height
        width = +svg.attr("width"),
        height = +svg.attr("height")
        preserveAspectRatio = "xMinYMin meet"

    //color definition
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    //Creates a new simulation with the specified array of nodes
    var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function (d) { return d.id; }))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width/2.3, height/2.3))

    // adding links 
    //The g element is a container element for grouping related graphics together
    var link = svg.append("g")
        .attr("class", "links")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("stroke-width", function (d) { return Math.sqrt(d.value); });

    //adding nodes
    var node = svg.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .enter().append("circle")
        .attr("r", 6)
        .attr("fill", function (d) { return color(d.group); })
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));


    //var text = svg.append("g")
    //  .attr("class", "text")
    //  .selectAll("circle")
    //  .data(graph.nodes)
    //  .enter().append("id")
    //  .attr("cx", "12")
    //  .attr("cy", ".35em")
    //  .attr("text-anchor", "middle")
    //  .text(function(d) { return d.id });

    // adding title
    node.append("title")
        .text(function (d) { return (d.id); });

    var text = svg.append("g")
    .attr("class", "labels")
    .selectAll("text")
    .data(graph.nodes)
    .enter().append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.id });

    simulation
        .nodes(graph.nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(graph.links);

    // ticked functionality 
    function ticked() {
        link
            .attr("x1", function (d) { return d.source.x; })
            .attr("y1", function (d) { return d.source.y; })
            .attr("x2", function (d) { return d.target.x; })
            .attr("y2", function (d) { return d.target.y; });

        node
            .attr("cx", function (d) { return d.x; })
            .attr("cy", function (d) { return d.y; })
            .call(force.drag);
    }

    //The data and the circle element’s position are updated during the drag event
    // when dragged
    function dragstarted(d) {
        if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    }

    // when dragged completed
    function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    }

    // when dragged ended
    function dragended(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }

1 个答案:

答案 0 :(得分:0)

您还必须在DispatchGroup函数中移动文本:

tick

以下是您更改的代码:

text.attr("x", function(d) {
  return d.x;
})
.attr("y", function(d) {
  return d.y;
});
var graph = {
  "nodes": [{
      "id": "xxx1",
      "group": 3
    }, {
      "id": "xxx2",
      "group": 1
    }, {
      "id": "xxx3",
      "group": 1
    }

  ],
  "links": [{
    "source": "xxx1",
    "target": "xxx2",
    "value": 42
  }, {
    "source": "xxx2",
    "target": "xxx3",
    "value": 6
  }, {
    "source": "xxx1",
    "target": "xxx3",
    "value": 13
  }]
};


// create the construct/canvas for drawing
var svg = d3.select("svg")
  //set width/height
width = +svg.attr("width"),
  height = +svg.attr("height")
preserveAspectRatio = "xMinYMin meet"

//color definition
var color = d3.scaleOrdinal(d3.schemeCategory20);

//Creates a new simulation with the specified array of nodes
var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(function(d) {
    return d.id;
  }))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width / 2.3, height / 2.3))

// adding links 
//The g element is a container element for grouping related graphics together
var link = svg.append("g")
  .attr("class", "links")
  .selectAll("line")
  .data(graph.links)
  .enter().append("line")
  .attr("stroke-width", function(d) {
    return Math.sqrt(d.value);
  });

//adding nodes
var node = svg.append("g")
  .attr("class", "nodes")
  .selectAll("circle")
  .data(graph.nodes)
  .enter().append("circle")
  .attr("r", 6)
  .attr("fill", function(d) {
    return color(d.group);
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

// adding title
node.append("title")
  .text(function(d) {
    return (d.id);
  });

var text = svg.append("g")
  .attr("class", "labels")
  .selectAll("text")
  .data(graph.nodes)
  .enter().append("text")
  .attr("dx", 12)
  .attr("dy", ".35em")
  .text(function(d) {
    return d.id
  });

simulation
  .nodes(graph.nodes)
  .on("tick", ticked);

simulation.force("link")
  .links(graph.links);

// ticked functionality 
function ticked() {
  link
    .attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    });

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

  text.attr("x", function(d) {
      return d.x;
    })
    .attr("y", function(d) {
      return d.y;
    });


}

//The data and the circle element’s position are updated during the drag event
// when dragged
function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

// when dragged completed
function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

// when dragged ended
function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
.links line {
  stroke: #999;
  stroke-opacity: 0.5;
}

.nodes circle {
  stroke: #fff;
  stroke-width: 1.2px;
}