D3力布局:直线而不是曲线的链接(但只有一些链接) [英] D3 force layout: Straight line instead of curve for links (but only for some links)

查看:263
本文介绍了D3力布局:直线而不是曲线的链接(但只有一些链接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 D3 jsfiddle



这个图的唯一让我困扰的是,如果两个节点之间只有一个链接,它被绘制为一条曲线。我认为如果这样的链接只是直线(箭头会很好)会更好。让我们说,微软和亚马逊之间应该是一条直线(带箭头)。



如何实现这一点?

解决方案

这很容易。在 linkArc(d)方法中,只要将 dr 参数设置为0即可默认一个,如果还有更多。这样,节点之间不会有任何曲线。



第一步,将确定有多少邻居。一个简单的方法就像下面刚刚从链接定义节点,虽然它不是最佳的。

 链接。 forEach(function(d){
if(nodes [d.source.name] .children == undefined){
nodes [d.source.name] .children = 0;
}
nodes [d.source.name] .children ++
});

一旦你这样做,你可以调整线的曲线如下:

  function linkArc(d){
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr =(nodes [d.target.name] .children> 1& nodes [d.source.name] .children> 1)?Math.sqrt (dx * dx + dy * dy):0;
returnM+ d.source.x +,+ d.source.y +A+ dr +,+ dr +0 0,1+ d.target.x + ,+ d.target.y;
}

结果将是这样:





我是确保有更好的方法来解决这个问题,但它是一个开始。
希望这有帮助。


I have this D3 jsfiddle that produces following diagram:

The only thing that bothers me about this diagram is that if there is only one link between two nodes, it is drawn as a curve. I think it would be much better if such links were just straight lines (arrow would be fine). Let's say between Microsoft and Amazon should be just a straight line (with arrow). The same between Oracle and Google, Sony and LG, etc.

How to achieve this?

解决方案

It's very easy. In your linkArc(d) method, just set the dr parameter to 0 if there is only 1 child, or the default one, if there are more. This way there won't be any curve between the nodes.

The first step though, will be to determine how many neighbours there are. A simple way would be like the following just after you define the nodes from the links, though it is not optimal.

links.forEach(function(d) {
    if (nodes[d.source.name].children==undefined) {
        nodes[d.source.name].children=0;
    }
    nodes[d.source.name].children++
});

Once you do that, you can adjust the curve of the line as follows:

function linkArc(d) {
  var dx = d.target.x - d.source.x,
      dy = d.target.y - d.source.y,
      dr = (nodes[d.target.name].children>1 & nodes[d.source.name].children>1)?Math.sqrt(dx * dx + dy * dy):0;
  return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}

The result will be like this:

I am sure that there are much better ways to tackle this, but it is a start. Hope this helps.

这篇关于D3力布局:直线而不是曲线的链接(但只有一些链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆