【问题标题】:Add labels to force layout where data is only client side (D3)添加标签以强制布局数据仅在客户端 (D3)
【发布时间】:2018-01-08 15:57:54
【问题描述】:

我正在使用强制布局示例here

我需要给节点添加标签。我见过的所有例子都使用这样的东西:

node.append("text")
  .attr("dx", 12)
  .attr("dy", ".35em")
  .text(function(d) { return d.name });

但是当有一个函数在本地数据上被调用时这有效,例如:

d3.json("graph.json", function(error, json) {

但在我的示例中,数据都是客户端,因此不需要 d3.json 来传递它。在这种情况下,如何为每个节点添加标签?以下是我正在使用的代码:

<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

// set a width and height for our SVG
var width = 1000,
height = 800;

// setup links
var links = [
{ source: 'Baratheon', target:'Lannister' },
{ source: 'Baratheon', target:'Stark' },
{ source: 'Lannister', target:'Stark' },
{ source: 'Stark', target:'Bolton' },
];

// create empty nodes array
var nodes = {};

// compute nodes from links data
links.forEach(function(link) {
    link.source = nodes[link.source] ||
        (nodes[link.source] = {name: link.source});
    link.target = nodes[link.target] ||
        (nodes[link.target] = {name: link.target});
});


// add a SVG to the body for our viz
var svg=d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height);

// use the force
var force = d3.layout.force()
    .size([width, height])
    .nodes(d3.values(nodes))
    .links(links)
    .on("tick", tick)
    .linkDistance(300)
    .start();

// add links
var link = svg.selectAll('.link')
    .data(links)
    .enter().append('line')
    .attr('class', 'link');

// add nodes
var node = svg.selectAll('.node')
    .data(force.nodes())
    .enter().append('circle')
    .attr('class', 'node')
    .attr('r', width * 0.01);


// what to do
function tick(e) {

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

    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; });

}

</script>

【问题讨论】:

    标签: javascript d3.js force-layout


    【解决方案1】:

    您引用的标记示例有效,因为每个节点都通过.data() 方法绑定到一个对象。这些对象中的每一个都有一个name 属性,其中包含节点的标签。

    在您的代码中,您已经进行了此设置!您的节点绑定到 force.nodes() 对象数组,其子对象都具有 name 属性。您所要做的就是致电node.text(function(d) { return d.name })

    默认情况下,这些标签是不可见的。有关如何显示节点标签的想法,请参阅 this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2017-06-27
      • 2013-08-21
      • 2015-05-04
      • 2013-06-10
      • 2016-06-05
      相关资源
      最近更新 更多