【问题标题】:D3 Force Graph With Arrows and Curved Edges - shorten links so arrow doesnt overlap nodes带有箭头和弯曲边缘的 D3 力图 - 缩短链接,使箭头不与节点重叠
【发布时间】:2019-02-20 19:26:34
【问题描述】:

我刚刚通读了这篇文章 - Links and Arrowheads to terminate at borders of nodes in D3 - 但是我正在努力将他的答案(在他的弯曲链接上)与我的示例(我认为实际上)为我的链接使用更简单/不同的弯曲边缘。

在过去的 20-30 分钟内,我一直在研究我的问题的可重现示例,其中显示了力图,但是由于某种原因,该图没有出现(即使代码 sn-p 没有引发错误) .它不可避免地是一堆代码(重新创建一个 d3 力图),尽管只需要修复一小部分。首先,这里是代码sn-p:

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

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',13)
    .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 = svg.select("g.links")
  .selectAll("path")
  .data(linksData)
  .enter()
  .append("path")
  .attr('stroke', '#666666')
  .attr('fill', 'transparent')
  .attr("stroke-width", 2)
  .attr('marker-end', 'url(#arrowhead)')

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() {
  links.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;
  });

    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>

对于初学者来说,任何关于修复代码 sn-p 以显示图表的帮助将不胜感激。

然而,主要问题是箭头进入节点,而我宁愿没有重叠。这个jsfiddle在箭头和我认为看起来更好的节点之间有一个间隙-http://jsfiddle.net/yeQS2/89/-尽管我认为对于我的示例,我希望箭头和节点之间的间隙更大。

我认为我需要更新的是 ticked() 函数:

function ticked() {
  links.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;
  });

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

我正在积极修复可重现的示例。我在这方面非常努力,并且认为这是很多人在尝试制作美观的 d3 力布局时会遇到的问题。对此的任何帮助表示赞赏!

编辑:感谢帮助图表正常工作的人 - 我进去并在链接上使填充透明,所以只显示笔划!

Edit2:不确定是否允许,但这是针对我的一个大项目,我会在 2 天内赏金这篇文章,或者如果更早,肯定会赏金获胜者。

【问题讨论】:

  • 试图关闭为重复。请参阅我的回答here。让我编写一个示例,看看它是否符合您的需求。
  • 现在也在浏览你的帖子,谢谢分享
  • 决定只发布它作为答案,因为我遇到了麻烦,让它与您的代码一起运行。

标签: d3.js force-layout


【解决方案1】:

在我的回答 here 中应用相同的想法。

生产:

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

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 = svg.select("g.links")
  .selectAll("path")
  .data(linksData)
  .enter()
  .append("path")
  .attr('stroke', '#666666')
  .attr('fill', 'transparent')
  .attr("stroke-width", 2)
  .attr('marker-end', 'url(#arrowhead)')

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() {
  links.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
  links.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;
  });

  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>

关键是这个:

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

    // length of current path
    var pl = this.getTotalLength(),
      // radius of circle plus backoff
      r = (12) + 30, //<-- 12 is your radius 30 is the "back-off" distance
      // 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;
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多