"nodes": [
{
"data": {
"id": 1,
"desc": "Rohit",
"pos": [
121.0284957885742,
116.3165512084961,
59.36788940429688
]
}
},
{
"data": {
"id": 2,
"desc": "Deep",
"pos": [
12.10284957885742,
116.3165512084961,
5.936788940429688
]
}
},
"data": {
"id": 3,
"desc": "Deepa",
"pos": [
12.10284957885742,
11.63165512084961,
5.936788940429688
]
}
}
]
以上是节点的坐标。
"edges": [
{
"data": {
"id": "1_2",
"source": 1,
"target": 2
}
}
以上是链接的输入示例。如何根据给定的坐标在d3中创建和分配节点的位置?我已经尝试了以像素为单位的坐标,但上面的样本集不包含任何单位。
完整代码在下面…
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
fill: blue;
stroke: black;
stroke-width: 2px;
}
.node.visited {
fill: red;
}
.link {
stroke-width: 2px;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var width = 640,
height = 480;
var links = [{
source: 'Rohit',
target: 'Deep'
},
{
source: 'Deep',
target: 'Deepa'
},
{
source: 'Deepa',
target: 'Rohit'
},
];
var nodes = [{
"id": 1,
"desc": "Rohit",
"x": 121.0284957885742,
"y": 116.3165512084961,
"z": 59.36788940429688
},
{
"id": 2,
"desc": "Deep",
"x": 12.10284957885742,
"y": 116.3165512084961,
"z": 5.936788940429688
},
{
"id": 3,
"desc": "Deepa",
"x": 12.10284957885742,
"y": 11.63165512084961,
"z": 135.936788940429688
}
];
//adding svg to body
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var defs = svg.append('defs');
var gradient = defs
.append('linearGradient')
.attr('id', 'svgGradient')
.attr('x1', '0%')
.attr('x2', '10%')
.attr('y1', '0%')
.attr('y2', '10%');
gradient
.append('stop')
.attr('class', 'start')
.attr('offset', '0%')
.attr('start-color', 'red')
.attr('start-opacity', 1);
gradient
.append('stop')
.attr('class', 'end')
.attr('offset', '100%')
.attr('stop-color', 'blue')
.attr('stop-opacity', 1);
var force = d3.layout.force()
.size([width, height])
.nodes(d3.values(nodes))
.links(links)
.on("tick", tick)
.linkDistance(300)
.start();
var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link')
.attr('stroke', 'url(#svgGradient)');
var node = svg.selectAll('.node')
.data(force.nodes())
.enter().append('circle')
.attr('class', 'node')
.on("click", clicked)
.attr('r', width * 0.03);
function clicked(event, d) {
if (event.defaultPrevented) return; // dragged
d3.select(this).transition()
.style("fill", "black")
.attr("r", width * 0.2)
.transition()
.attr("r", width * 0.03)
.transition()
.style("fill", "blue")
//.attr("fill", d3.schemeCategory10[d.index % 10]);
}
//define the tick func.
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>
</body>
</html>
对上述代码段的任何更改都是可以接受的。接下来我可以尝试什么?
编辑
我运行了代码但节点不接受分配给它们的位置。
正如你所看到的,在力导向图中没有定义的边,而且节点的位置也不随坐标的变化而变化。
1条答案
按热度按时间eivnm1vs1#
试试这个解决方案: