在力导向图中以弯曲链接为中心文本

问题描述 投票:2回答:1

这是第二个问题,它建立在我之前的一个问题 - D3 Force Graph With Arrows and Curved Edges - shorten links so arrow doesnt overlap nodes - 关于如何缩短d3力图的曲线链接。

我最近的斗争涉及将放置在链接顶部的文本居中,实际上是在链接上。这是一个可重现的例子,显示了我的问题(为长代码道歉。创建一个可重现的例子需要很多,尽管我目前只处理它的一小部分):

const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")

var graphs = {
  "nodes": [{
      "name": "Peter",
      "label": "Person",
      "id": 1
    },
    {
      "name": "Michael",
      "label": "Person",
      "id": 2
    },
    {
      "name": "Neo4j",
      "label": "Database",
      "id": 3
    },
    {
      "name": "Graph Database",
      "label": "Database",
      "id": 4
    }
  ],
  "links": [{
      "source": 1,
      "target": 2,
      "type": "KNOWS",
      "since": 2010
    },
    {
      "source": 1,
      "target": 3,
      "type": "FOUNDED"
    },
    {
      "source": 2,
      "target": 3,
      "type": "WORKS_ON"
    },
    {
      "source": 3,
      "target": 4,
      "type": "IS_A"
    }
  ]
}

svg.append('defs').append('marker')
  .attr('id', 'arrowhead')
  .attr('viewBox', '-0 -5 10 10')
  .attr('refX', 0)
  .attr('refY', 0)
  .attr('orient', 'auto')
  .attr('markerWidth', 13)
  .attr('markerHeight', 13)
  .attr('xoverflow', 'visible')
  .append('svg:path')
  .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
  .attr('fill', '#999')
  .style('stroke', 'none');

const simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(d => d.id))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(100, 100));

let linksData = graphs.links.map(link => {
  var obj = link;
  obj.source = link.source;
  obj.target = link.target;
  return obj;
})

const links = linksG
  .selectAll("g")
  .data(graphs.links)
  .enter().append("g")
  .attr("cursor", "pointer")

const linkLines = links
  .append("path")
  .attr('stroke', '#000000')
  .attr('opacity', 0.75)
  .attr("stroke-width", 1)
  .attr("fill", "transparent")
  .attr('marker-end', 'url(#arrowhead)');

const linkText = links
  .append("text")
  .attr("x", d => (d.source.x + (d.target.x - d.source.x) * 0.5))
  .attr("y", d => (d.source.y + (d.target.y - d.source.y) * 0.5))
  .attr('stroke', '#000000')
  .attr("text-anchor", "middle")
  .attr('opacity', 1)
  .text((d,i) => `${i}`);

const nodes = nodesG
  .selectAll("g")
  .data(graphs.nodes)
  .enter().append("g")
  .attr("cursor", "pointer")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

const circles = nodes.append("circle")
  .attr("r", 12)
  .attr("fill", "000000")

nodes.append("title")
  .text(function(d) {
    return d.id;
  });

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

simulation.force("link", d3.forceLink().links(linksData)
  .id((d, i) => d.id)
  .distance(150));

function ticked() {
  linkLines.attr("d", function(d) {
    var dx = (d.target.x - d.source.x),
      dy = (d.target.y - d.source.y),
      dr = Math.sqrt(dx * dx + dy * dy);
    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
  });

  // recalculate and back off the distance
  linkLines.attr("d", function(d) {

    // length of current path
    var pl = this.getTotalLength(),
      // radius of circle plus backoff
      r = (12) + 30,
      // position close to where path intercepts circle
      m = this.getPointAtLength(pl - r);

    var dx = m.x - d.source.x,
      dy = m.y - d.source.y,
      dr = Math.sqrt(dx * dx + dy * dy);

    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
  });

  linkText
    .attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
    .attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })

  nodes
    .attr("transform", d => `translate(${d.x}, ${d.y})`);
    

}

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

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

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>

</head>

<body>
  <svg id="mySVG" width="500" height="500">
  <g class="links" />
	<g class="nodes" />
</svg>

我知道我的代码的问题是在这里设置linkText的x和y值:

linkText
  .attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
  .attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })

......还有我早期的代码。我不知道如何更新这些函数以解释链接是曲线(不是从节点到节点的直线)的事实。

我的项目的较大力图具有更多的链接和节点,并且文本在弯曲linkLines的中心上的定位将是更可取的。

对此有任何帮助表示赞赏!

javascript d3.js svg force-layout
1个回答
2
投票

有几种不同的方法可以解决这个问题。最明显的两个是:

  1. 使用getPointAtLength()获得<path>的中间位置,并将文本放在那里;
  2. 使用<textPath>元素。

在我的解决方案中,我将选择#2主要是因为,使用文本路径,数字可以根据路径的方向翻转,其中一些最终颠倒(我假设这是你想要的)。

所以,我们追加textPaths ......

const linkText = links
    .append("text")
    .attr("dy", -4)
    .append("textPath")
    .attr("xlink:href", function(_, i) {
        return "#path" + i
    })
    .attr("startOffset", "50%")
    .text((d, i) => `${i}`);

...给了路径唯一的ID:

.attr("id", function(_, i) {
    return "path" + i
})

这是包含这些更改的代码:

const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")

var graphs = {
  "nodes": [{
      "name": "Peter",
      "label": "Person",
      "id": 1
    },
    {
      "name": "Michael",
      "label": "Person",
      "id": 2
    },
    {
      "name": "Neo4j",
      "label": "Database",
      "id": 3
    },
    {
      "name": "Graph Database",
      "label": "Database",
      "id": 4
    }
  ],
  "links": [{
      "source": 1,
      "target": 2,
      "type": "KNOWS",
      "since": 2010
    },
    {
      "source": 1,
      "target": 3,
      "type": "FOUNDED"
    },
    {
      "source": 2,
      "target": 3,
      "type": "WORKS_ON"
    },
    {
      "source": 3,
      "target": 4,
      "type": "IS_A"
    }
  ]
}

svg.append('defs').append('marker')
  .attr('id', 'arrowhead')
  .attr('viewBox', '-0 -5 10 10')
  .attr('refX', 0)
  .attr('refY', 0)
  .attr('orient', 'auto')
  .attr('markerWidth', 13)
  .attr('markerHeight', 13)
  .attr('xoverflow', 'visible')
  .append('svg:path')
  .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
  .attr('fill', '#999')
  .style('stroke', 'none');

const simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(d => d.id))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(100, 100));

let linksData = graphs.links.map(link => {
  var obj = link;
  obj.source = link.source;
  obj.target = link.target;
  return obj;
})

const links = linksG
  .selectAll("g")
  .data(graphs.links)
  .enter().append("g")
  .attr("cursor", "pointer")

const linkLines = links
  .append("path")
  .attr("id", function(_, i) {
    return "path" + i
  })
  .attr('stroke', '#000000')
  .attr('opacity', 0.75)
  .attr("stroke-width", 1)
  .attr("fill", "transparent")
  .attr('marker-end', 'url(#arrowhead)');

const linkText = links
  .append("text")
  .attr("dy", -4)
  .append("textPath")
  .attr("xlink:href", function(_, i) {
    return "#path" + i
  })
  .attr("startOffset", "50%")
  .attr('stroke', '#000000')
  .attr('opacity', 1)
  .text((d, i) => `${i}`);

const nodes = nodesG
  .selectAll("g")
  .data(graphs.nodes)
  .enter().append("g")
  .attr("cursor", "pointer")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

const circles = nodes.append("circle")
  .attr("r", 12)
  .attr("fill", "000000")

nodes.append("title")
  .text(function(d) {
    return d.id;
  });

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

simulation.force("link", d3.forceLink().links(linksData)
  .id((d, i) => d.id)
  .distance(150));

function ticked() {
  linkLines.attr("d", function(d) {
    var dx = (d.target.x - d.source.x),
      dy = (d.target.y - d.source.y),
      dr = Math.sqrt(dx * dx + dy * dy);
    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
  });

  // recalculate and back off the distance
  linkLines.attr("d", function(d) {

    // length of current path
    var pl = this.getTotalLength(),
      // radius of circle plus backoff
      r = (12) + 30,
      // position close to where path intercepts circle
      m = this.getPointAtLength(pl - r);

    var dx = m.x - d.source.x,
      dy = m.y - d.source.y,
      dr = Math.sqrt(dx * dx + dy * dy);

    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
  });

  linkText
    .attr("x", function(d) {
      return (d.source.x + (d.target.x - d.source.x) * 0.5);
    })
    .attr("y", function(d) {
      return (d.source.y + (d.target.y - d.source.y) * 0.5);
    })

  nodes
    .attr("transform", d => `translate(${d.x}, ${d.y})`);


}

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

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

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>

</head>

<body>
  <svg id="mySVG" width="500" height="500">
  <g class="links" />
	<g class="nodes" />
</svg>

另一方面,如果您不希望某些文本颠倒过来,请使用getPointAtLength()来获取路径的中间位置,即方法#1:

.attr("x", function(d) {
    const length = this.previousSibling.getTotalLength();
    return this.previousSibling.getPointAtLength(length/2).x
})
.attr("y", function(d) {
    const length = this.previousSibling.getTotalLength();
    return this.previousSibling.getPointAtLength(length/2).y
})

这是演示:

const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")

var graphs = {
  "nodes": [{
      "name": "Peter",
      "label": "Person",
      "id": 1
    },
    {
      "name": "Michael",
      "label": "Person",
      "id": 2
    },
    {
      "name": "Neo4j",
      "label": "Database",
      "id": 3
    },
    {
      "name": "Graph Database",
      "label": "Database",
      "id": 4
    }
  ],
  "links": [{
      "source": 1,
      "target": 2,
      "type": "KNOWS",
      "since": 2010
    },
    {
      "source": 1,
      "target": 3,
      "type": "FOUNDED"
    },
    {
      "source": 2,
      "target": 3,
      "type": "WORKS_ON"
    },
    {
      "source": 3,
      "target": 4,
      "type": "IS_A"
    }
  ]
}

svg.append('defs').append('marker')
  .attr('id', 'arrowhead')
  .attr('viewBox', '-0 -5 10 10')
  .attr('refX', 0)
  .attr('refY', 0)
  .attr('orient', 'auto')
  .attr('markerWidth', 13)
  .attr('markerHeight', 13)
  .attr('xoverflow', 'visible')
  .append('svg:path')
  .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
  .attr('fill', '#999')
  .style('stroke', 'none');

const simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(d => d.id))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(100, 100));

let linksData = graphs.links.map(link => {
  var obj = link;
  obj.source = link.source;
  obj.target = link.target;
  return obj;
})

const links = linksG
  .selectAll("g")
  .data(graphs.links)
  .enter().append("g")
  .attr("cursor", "pointer")

const linkLines = links
  .append("path")
  .attr('stroke', '#000000')
  .attr('opacity', 0.75)
  .attr("stroke-width", 1)
  .attr("fill", "transparent")
  .attr('marker-end', 'url(#arrowhead)');

const linkText = links
  .append("text")
  .attr("x", function(d) {
    const length = this.previousSibling.getTotalLength();
    return this.previousSibling.getPointAtLength(length / 2).x
  })
  .attr("y", function(d) {
    const length = this.previousSibling.getTotalLength();
    return this.previousSibling.getPointAtLength(length / 2).y
  })
  .attr('stroke', '#000000')
  .attr("text-anchor", "middle")
  .attr("dominant-baseline", "central")
  .attr('opacity', 1)
  .text((d, i) => `${i}`);

const nodes = nodesG
  .selectAll("g")
  .data(graphs.nodes)
  .enter().append("g")
  .attr("cursor", "pointer")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

const circles = nodes.append("circle")
  .attr("r", 12)
  .attr("fill", "000000")

nodes.append("title")
  .text(function(d) {
    return d.id;
  });

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

simulation.force("link", d3.forceLink().links(linksData)
  .id((d, i) => d.id)
  .distance(150));

function ticked() {
  linkLines.attr("d", function(d) {
    var dx = (d.target.x - d.source.x),
      dy = (d.target.y - d.source.y),
      dr = Math.sqrt(dx * dx + dy * dy);
    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
  });

  // recalculate and back off the distance
  linkLines.attr("d", function(d) {

    // length of current path
    var pl = this.getTotalLength(),
      // radius of circle plus backoff
      r = (12) + 30,
      // position close to where path intercepts circle
      m = this.getPointAtLength(pl - r);

    var dx = m.x - d.source.x,
      dy = m.y - d.source.y,
      dr = Math.sqrt(dx * dx + dy * dy);

    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
  });

  linkText
    .attr("x", function(d) {
      const length = this.previousSibling.getTotalLength();
      return this.previousSibling.getPointAtLength(length / 2).x
    })
    .attr("y", function(d) {
      const length = this.previousSibling.getTotalLength();
      return this.previousSibling.getPointAtLength(length / 2).y
    })

  nodes
    .attr("transform", d => `translate(${d.x}, ${d.y})`);


}

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

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

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>

  </head>

  <body>
    <svg id="mySVG" width="500" height="500">
  <g class="links" />
	<g class="nodes" />
</svg>

在这里,我假设<path><text>的前兄弟。如果在实际代码中不是这种情况,请相应地更改它。

© www.soinside.com 2019 - 2024. All rights reserved.