[英]How to draw a simple directed graph
我可以像這樣繪制一個簡單的有向力圖:
<html>
<head>
<meta charset='utf-8'>
<title>Force Layout Example 1</title>
<style>
.node {
fill: #ccc;
stroke: #fff;
stroke-width: 2px;
}
.link {
stroke: #777;
stroke-width: 2px;
}
</style>
</head>
<body>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script>
var width = 640,
height = 480;
constant = 174
var nodes = [
{ x: constant, y: 215 , width:50,height:50 },
{ x: 2*constant, y: 215 ,width:50,height:50 },
{ x: 3*constant, y: 215 ,width:50,height:50 },
{ x: 4*constant, y: 215 ,width:50,height:50 }
];
var links = [
{ source: 0, target: 1 }
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links);
force.linkDistance(width/2);
var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link');
var node = svg.selectAll('.node')
.data(nodes)
.enter().append('rect')
.attr('class', 'node');
force.on('end', function() {
node.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return 215; })
.attr('width', function(d) { return d.width; })
.attr('height', function(d) { return d.height; });
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; });
});
force.start();
</script>
</body>
</html>
這給了我 output 之類的:
我想實現這一點:
我不確定如何更改上述代碼以在矩形內添加文本。 我也希望矩形是圓形的!
我為文本嘗試了以下內容:
node.append('text').text('A')
.attr('x', 174)
.attr('y', 250)
.attr('fill', 'black')
但是,這是行不通的。 我不確定如何實現這一目標。 有什么線索嗎?
提前致謝。
以該樣式插入文本的實際代碼如下:
node.append("text").style("text-anchor", "middle")
.style("pointer-events", "none")
.style("font-weight", 900)
.attr("fill", "white")
.style("stroke-width", "0.3px")
.style("font-size", "16px")
.attr("y", function (d){return d.height/2+6;})
.attr("x", function (d){return d.width/2;})
.text(function (d) {return d.label;});
這是一個與您的圖像非常相似的小提琴。 一些顯着的變化:
g
(組)元素,然后添加了rect
AND text
。 然后根據node.x
和node.y
字段轉換這些元素,這會同時移動 text 和 rect。rx
和ry
四舍五入,並使用.style("fill", "#2376B2")
。希望這可以幫助!
我制作了一個免費的輕量級庫,可能對其他人有用:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.