0
我正在創建一個強制定向圖,並且希望將文本添加到我的圖節點。D3.js - 在強制定向圖中向節點添加文本
我可以在控制檯中看到文本元素被追加到圓上,但它沒有任何價值。
爲圖中的代碼如下:
var force = d3.layout.force()
.charge(-120)
.linkDistance(40);
var width = $(document).width() - 550;
height = $(document).height() - 300;
var colour = d3.scale.category20();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("style", "outline: thin solid black;");
force
.size([width, height])
.nodes(convertedInfo.nodes)
.links(convertedInfo.links)
.start();
//Adding nodes and data
var link = svg.selectAll("link")
.data(convertedInfo.links)
.enter()
.append("line")
.attr("stroke-width", 3)
.attr("class", "link")
.attr("stroke", "grey");
var node = svg.selectAll("node")
.data(convertedInfo.nodes)
.enter()
.append("circle")
.attr("r", 7)
.attr("class", "node")
.style("fill", function(d) {return colour(d.domain_count);})
.append('text');
var text = svg.selectAll("text")
.data(convertedInfo.nodes)
.enter()
.append("text")
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text('text')
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
//Fisheye view
var fisheye = d3.fisheye.circular()
.radius(70)
.distortion(2);
svg.on("mousemove", function() {
fisheye.focus(d3.mouse(this));
node.each(function(d) { d.fisheye = fisheye(d); })
.attr("cx", function(d) { return d.fisheye.x; })
.attr("cy", function(d) { return d.fisheye.y; })
.attr("r", function(d) { return d.fisheye.z * 4.5; });
link.attr("x1", function(d) { return d.source.fisheye.x; })
.attr("y1", function(d) { return d.source.fisheye.y; })
.attr("x2", function(d) { return d.target.fisheye.x; })
.attr("y2", function(d) { return d.target.fisheye.y; });
});
force.on("tick", function() {
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("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
現在我只是把一個佔位符的text
值,這樣我可以看看它是否工作。
這段代碼有什麼問題?
如果'convertedInfo.nodes'是您給力佈局的東西,那麼您使用了錯誤的屬性名稱:'.cx'和'.cy'不是由佈局設置的。使用'.x'和'.y'。 – 2014-11-03 18:09:00
不幸的是,這仍然不起作用 – ALR 2014-11-03 18:25:33
其實,在控制檯中,我可以看到文本元素被追加,它沒有任何價值。如果我改變這行說'.text('text')',它仍然不起作用 – ALR 2014-11-03 18:31:21