force directed graph - 基于节点之间的连接数(卷)的链路宽度

时间:2016-12-06 14:29:40

标签: javascript d3.js

我是d3的新手,并尝试根据节点之间的连接数使链接的宽度动态化。比方说,我们有:

"links": [     
            { "source": a, "target": b},
            { "source": a, "target": b},
            { "source": b, "target": a},
            { "source": b, "target": c}]

a和b之间有3个连接,所以宽度应为3个像素; b和c之间有1个连接,所以宽度应该是1个像素。

代码:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script src="https://d3js.org/d3.v3.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/john-guerra/forceInABox/master/forceInABox.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>

  <style type="text/css">

.link {
    stroke: #999;
    stroke-opacity: .6;
}
.node text {
  pointer-events: none;
  font: 10px sans-serif;
  color: black;
}

  </style>

<title>OnlineQ</title>

</head>

<body>
     <div id="container" class="container">
           <div id="sidebar" style="display: none;">
                <div class="item-group">
                    <label class="item-label">Filter</label>
                    <div id="filterContainer" class="filterContainer checkbox-interaction-group"></div>
                </div>
            </div>  
            <div id="graphContainer" class="graphContainer">
  <script type="application/json" id="dataset">
   {
  "nodes": [
{"name":"a1","group":"Group1","type":"a","id":1,"class":"L"},
{"name":"a2","group":"Group2","type":"b","id":2,"class":"L"},
{"name":"a3","group":"Group3","type":"c","id":3,"class":"M"},
{"name":"a4","group":"Group4","type":"a","id":4,"class":"H"},
{"name":"a5","group":"Group2","type":"b","id":5,"class":"H"}
  ],
  "links": [
{"source":0,"target":1},
{"source":0,"target":1},
{"source":1,"target":0},
{"source":2,"target":3},
{"source":4,"target":3},
{"source":4,"target":3},
{"source":4,"target":3}
  ]
}
</script>

<script type='text/javascript'>//<![CDATA[

//Constants for the SVG
var width = 600,
    height = 600;

//Set up the colour scale
var color = d3.scale.category20();

//Set up the force layout
var force = d3.layout.forceInABox()
    .charge(-120)
    .linkDistance(50)
    .linkStrengthInterCluster(0.001)
    .gravityToFoci(0.2)
    .gravityOverall(0.1)
    .size([width, height])
    .groupBy("group");


//Append a SVG to the body of the html page. Assign this SVG as an object to svg
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var linkedByIndex = {};

//Read the data from the dataset element 
var dataset = document.getElementById('dataset').innerHTML;
graph = JSON.parse(dataset);

//Creates the graph data structure out of the json data
force.nodes(graph.nodes)
    .links(graph.links)
    .start();

//Create all the line svgs but without locations yet
var link = svg.selectAll(".link")
    .data(graph.links)
    .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", 1)
     .style("marker-end",  "url(#source)") //Added ;

//Do the same with the circles for the nodes - no 

var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("g")
    .attr("class", function (d) {
        if (d.type == "a") {
           return "BA node";
        } else {
           return "other node";
        }
    })
    .call(force.drag);

d3.selectAll(".BA").append("rect")
    .attr("width", 10)
    .attr("height", 10)
    .attr("stroke", "black")
    .attr("stroke-width", function(d) {
            if (d.class == "L") {return 0}
            if (d.class == "M") {return 1}
            else    {return 2}
    ;})
    .style("fill", function (d) { return color(d.group);    
});

d3.selectAll(".other").append("circle")
    .attr("r", 8)
    .attr("stroke", "black")
    .attr("stroke-width", function(d) {
            if (d.class == "L") {return 0}
            if (d.class == "M") {return 1}
            else    {return 2}
    ;})

    .style("fill", function (d) { return color(d.group);
});

node.append("text")
    .attr("dx", 10)
    .attr("dy", ".35em")
    .style("stroke", "white")
    .style("stroke-width", 2)
    .text(function(d) { return d.name; });

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

svg.append("arrow").selectAll("marker")
    .data(["source", "target"])
  .enter().append("marker")
    .attr("id", function(d) { return d; })
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 25)
    .attr("refY", 0)
    .attr("markerWidth", 8)
    .attr("markerHeight", 8)
    .attr("orient", "auto")
  .append("path")
    .attr("d", "M0,-5L10,0L0,5 L10,0 L0, -5")
    .style("stroke", "#4679BD")
    .style("opacity", "0.6");



//Now we are giving the SVGs co-ordinates - the force layout is generating the co-ordinates which this code is using to update the attributes of the SVG elements
force.on("tick", function (e) {

    force.onTick(e);

    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("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")"; });    

    graph.links.forEach(function(d) {
          linkedByIndex[d.source.index + "," + d.target.index] = 1;
          linkedByIndex[d.target.index + "," + d.source.index] = 1;
        });
});

    function neighboring(a, b) {
      return a.index == b.index || linkedByIndex[a.index + "," + b.index];
    }


</script>
           </div>
        </div>

</body>

</html>

1 个答案:

答案 0 :(得分:3)

我们可以将原始数组更改为没有重复项的数组,并包含原始重复项的数字。我们将使用该数字来设置链接的宽度。

所以,如果这是你的阵列:

var links = [{
    "source": a,
    "target": b
}, {
    "source": a,
    "target": b
}, {
    "source": b,
    "target": a
}, {
    "source": b,
    "target": c
}];

让我们先按顺序放置每个对象的所有属性:

links.forEach(function(d) {
    var sourceTemp = d.source, targetTemp = d.target;
    if (d.source > d.target) {
        d.source = targetTemp;
        d.target = sourceTemp;
    }
});

然后,我们将计算有多少链接相等:

var counter = {};

links.forEach(function(obj) {
    var key = JSON.stringify(obj);
    counter[key] = (counter[key] || 0) + 1
});

然后,我们将填充你的最终数组:

var finalArray = [];

for (var key in counter) {
    var tempkey = key.substring(0, key.length - 1) + ",\"value\":" + counter[key] + "}";
    finalArray.push(tempkey)
};

当我使用JSON.stringify来计算重复的对象时,让我们解析它:

finalArray.forEach(function(d, i, array) {
    array[i] = (JSON.parse(d))
})

所以,最后,如果你记录了finalArray,你就会得到这个:

[
    {"source": "a","target": "b","value": 3},           
    {"source": "b","target": "c","value": 1}
];

最后,将finalArray定义为链接的数据,并使用value设置链接的宽度:

.style("stroke-width", d => d.value)

使用原始阵列检查此演示中的控制台:

var links = [{
        "source": "a",
        "target": "b"
    }, {
        "source": "a",
        "target": "b"
    }, {
        "source": "b",
        "target": "a"
    }, {
        "source": "b",
        "target": "c"
    }];

    links.forEach(function(d) {
        var sourceTemp = d.source, targetTemp = d.target;
        if (d.source > d.target) {
            d.source = targetTemp;
            d.target = sourceTemp;
        }
    });

    var counter = {};

    links.forEach(function(obj) {
        var key = JSON.stringify(obj);
        counter[key] = (counter[key] || 0) + 1
    });

    var finalArray = [];

    for (var key in counter) {
        var tempkey = key.substring(0, key.length - 1) + ",\"value\":" + counter[key] + "}";
        finalArray.push(tempkey)
    };

    finalArray.forEach(function(d, i, array) {
        array[i] = (JSON.parse(d))
    })

    console.log(finalArray);