Reputation: 281
I want to visualize a graph in d3js with the force-directed layout. I have been following this question, but I don't get it to work.
I created an jsfiddle, which can be found here. However, now the lines are not working, but the labels are how they should be. Oddly, when I execute it locally it is working but someday lines are shown twice, like this:
<g class="link-g">
<line class="link" x1="297.0210832552382" y1="122.48446414068198" x2="245.8066880510027" y2="240.1061616356794"></line>
<text>interaction</text>
<text x="271.4138856531205" y="181.2953128881807">interaction</text>
</g>
Anyway, what I do is the following. First the link and linktext.
var link = svg.selectAll(".link")
.data(links, function(d) {
return d.source.id + '-' + d.target.id;
});
link.enter()
.append("g")
.attr("class","link-g")
.append("line")
.attr("class", "link");
link.exit().remove();
var linktext = svg.selectAll(".link-g")
.append("text")
.text("label");
Then in the tick():
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;
});
What am I doing wrong? Thanks.
Upvotes: 0
Views: 396
Reputation: 221
You add attributes x1, x2, y1, y2
on the svg:g
element instead of the line
, that's why there is no visible links.
If you check the code : svg:g
elements have good values, and line
got no attribute.
Create a new variable to store your links, and add attributes on this variable:
var linkLine = link.enter()
.append("g")
.attr("class","link-g")
.append("line")
.attr("class", "link");
And update tick function
function tick(){
linkLine.attr("x1", function(d) {
return d.source.x;
})
/* ... (others attr) ... */
}
Upvotes: 1