How to update node data in a D3.js force graph? - javascript

I'm looking for a way to update multiple node attributes and appended elements on data change.
Here is how I'm trying to do it right now.
This function gets called every-time node or link data changes.
function restart() {
link = link.data(links);
link
.enter().insert("line", ".node")
.attr("class", "link")
.on('click' , function(d, i){
console.log(d);
links.splice(i,1);
restart();
})
.on("mouseover", function() {
d3.select(this).style("stroke","red");
d3.select(this).style("stroke-width","5px");
})
.on("mouseout", function() {
d3.select(this).style("stroke","#999");
d3.select(this).style("stroke-width","initial");
});
link
.exit().remove();
node = node.data(nodes);
node
.enter()
.append("g")
.attr("class", "node")
.call(node_drag);
node
.insert("circle", ".cursor")
.attr("r", function(d) { return calcSize(d.links+1); })
node
.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.links });
node
.exit().remove();
force.start();
}
The full code at the current state can be seen here: http://jsbin.com/takatugazo/edit?html,js,output
The expected behaviour is that when two nodes get dragged into each other they create a link and the more links they have the bigger they get.

Your appended text IS updating. The only issue seems to be that the instead of replacing the old text, it's adding a <text> element on top. If you just inspect a node, you'll find multiple <text> elements based on how many links it has. For some reason your code doesn't update the text the way it should.
Try removing the text element before you append one:
node.select("text").remove()
node
.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.links });
node
.exit().remove();
I made those changes in JS Bin and it seems to work for me (with a bit of a delay): http://jsbin.com/goqumutelu/edit?html,js,output
There is a delay in the dragend() function whenever is a link is pushed (not sure if intentional?) So if you don't want the delay: removing the timeout, or simply replacing the delay value (1500) to 0 should solve that: http://jsbin.com/hazecozumu/1/edit?html,js,output
About the size of the nodes, what's wrong it? How else did you want it to update?

Related

div element is getting appended outside the body

I want to implement a list on right-click of a data node. In order to do so I came across d3-context-menu plugin of d3.js. The problem I am facing is that the div element is getting appened outside the body tag.
I have never seen such an issue before.
I am following the plugin example given here:
http://plnkr.co/edit/hAx36JQhb0RsvVn7TomS?p=preview
This is the link to the library documentation:
https://github.com/patorjk/d3-context-menu
I have no clue why it is behaving in such manner. My code structure looks like this :
eventGroup = focusClip.selectAll(".event").data(data);
// Enter phase ---
eventGroupEnter = eventGroup.enter().append("svg");
eventGroupEnter.append("rect");
eventGroupEnter.append("circle");
eventGroupEnter.append("text");
// Event Group
eventGroup
.attr("class", "event")
.attr("x", function(d) {
return parseInt(x(d.time)) - 10;
}) // offset for the bg and center of dot
.attr("y", function(d) {
return parseInt(y(d.plotY));
})
.attr("width", function(d) {
return parseInt((d.label.length / 2)) + 60 + "em";
})
.attr("height", "20");
// Background
eventGroup.select("rect")
.attr("x", 0) // removes the "<rect> attribute x: Expected length, 'NaN'" Error
.attr("y", 4)
.attr("width", "100%")
.attr("height", "12")
.attr("fill", "url(#event-bg)");
menu = [{
title: "Item #1"
}];
// Dot
eventGroup.select("circle")
.attr("class", "dot")
.attr("r", 4)
.attr("cx", 10)
.attr("cy", 10)
.attr("fill", function(d) {
return d.evtColor ? d.evtColor : "#229ae5";
})
.attr("stroke", function(d) {
return d.evtColor ? d.evtColor : "#229ae5";
})
.attr("stroke-width", 2)
.on("contextmenu", d3.contextMenu(menu, function() {
console.log("Quick! Before the menu appears!");
}))
.on("mouseenter", tooltip.mouseover)
.on("mouseleave", tooltip.mouseout)
.on("click", annotateBox.click);
In order to explain it well I am adding the image of the chart:
The right click event is being called on the "dot" part of the event. Why would div element get appended outside the body?
This seems to be by design. If you look at the source code of that plugin, you'll see:
d3.selectAll('.d3-context-menu').data([1])
.enter()
.append('div')
.attr('class', 'd3-context-menu');
Since selectAll is called on the root, the div will be appended to the <html>, not to the <body>.
So, the author either did this intentionally or she/he forgot that d3.selectAll is different from selection.selectAll.
Here is a basic demo, click "Run code snippet", open your browser's dev tools and inspect the snippet window.
d3.selectAll("foo")
.data([1])
.enter()
.append("div")
.attr("class", "test")
<script src="https://d3js.org/d3.v3.min.js"></script>
You're gonna see this:
<html>
<head>...</head>
<body>...</body>
<div class="test"></div>
</html>

How to change d3.js text entry from within that text's onclick method?

My AngularJS app uses d3.js to draw a nice chart.
While drawing this chart, it uses paints some text on the screen.
I want to change that text when someone clicks on it based on the boolean value of myCondition. This is how I do it:
var nodeEnter = node.enter()
var myLabel = nodeEnter.append("text")
.attr("x", 50)
.attr("dy", "3")
.text("Hello World")
.style("fill-opacity", 0)
.style("cursor", "pointer")
.on("click", function(d) {
if (myCondition)
myLabel.text("Mars");
else
myLabel.text("Venus");
}
);
It sorta works. The value of the text does indeed change from Hello World to Mars or Venus. But there is a problem. This code is called within a recursive function and within a loop. That recursion + loop use the same code to draw numerous such texts on the SVG Container. So when I click this label, not only does it change the text that I want. It also changes the text in other places too! I don't want that. How can I prevent it?
I really just need a way I can address this or myself from within the click function so it knows I'm talking about the object. How?
Without knowing your recursive function and the loop, I'll try two different approaches, I hope that one of them works.
The first one is using this for the click event:
var myLabel = nodeEnter.append("text")
.attr("x", 50)
.attr("dy", "3")
.text("Hello World")
.style("fill-opacity", 0)
.style("cursor", "pointer")
.on("click", function(d) {
if (myCondition)
d3.select(this).text("Mars");
else
d3.select(this).text("Venus");
}
);
If this doesn't work, you can try to set a specific class to your different myLabel texts. Doing this, even if you have several myLabel in your SVG, each one has a unique class. Suppose that index is a specific value for the loop (like i). So, you can try:
var myLabel = nodeEnter.append("text")
.attr("x", 50)
.attr("dy", "3")
.attr("class", "myLabel" + index)//index is any value unique for the loop
.text("Hello World")
.style("fill-opacity", 0)
.style("cursor", "pointer")
.on("click", function(d) {
if (myCondition)
d3.selectAll(".myLabel" + index).text("Mars");
else
d3.selectAll(".myLabel" + index).text("Venus");
}
);

Displaying text over a node in a d3 force-layout graph

I am creating a force-layout graph using d3 and I am trying to make the name of a specific node appear when I mouse over that node. I know how to add the text before any mouse over effect and thought that I could just move that part of the code into the mouseover function but that did not work. I will also need to make the text disappear when I move the mouse off of the node. Here is the mouseover function where I attempt to add the name to the node:
function mouseover() {
d3.select(this).transition()
.duration(750)
.attr("r", function(d) {return d.size + 10;});
var labels = gnodes.append("text")
.text(function(d) { return d.name;})
console.log(labels);
}
Here is a link to a fiddle of the complete code as well:
http://jsfiddle.net/ohiobucks23/QvVU6/
If not using a tooltip per good recommendation by Bhatt, you will need to:
1) declare gnodes outside the drawGraph() function so that it is visible to the mouse functions, and
2) make the following changes to the mouse functions:
function mouseover(d) {
d3.select(this).transition()
.duration(750)
.attr("r", function (d) {return d.size + 10;});
// locate node and append text; add class to facilitate subsequent deletion
gnodes.filter(function (o) {return o.index === d.index;})
.append("text")
.attr("class", "nodetext")
.text(d.name);
}
function mouseout(d) {
d3.select(this).transition()
.duration(750)
.attr("r", function (d) {return d.size;});
// delete text based on class
d3.selectAll(".nodetext").remove();
}
Here is the complete FIDDLE. I changed the text of the root node element so that you can see that the mouseover function is really acting on the selected node.

Adding label to D3 path

I know how to add text element to simple node (append text). The problem is when I would like to add text to path surrounding several nodes. I have created example on http://jsfiddle.net/FEM3e/5/ Please ignore nodes in upper left corner. So I have two groups of nodes. And I would like to add text for each group. Printscreen of desired output http://dopisna.bencin.si/screenshot.png.
I set path in
force.on("tick", function () {
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
vis.selectAll("path")
.data(groups)
.attr("d", singlePath)
.enter().insert("path", "g")
.style("fill", groupFill)
.style("stroke", groupFill)
.style("stroke-width", 57)
.style("stroke-linejoin", "round")
.style("opacity", .7);
});
I have tried appending text with no success. I am asking for some hints.
OK then. The problem is that you're using text instead of textPath. I've modified your fiddle and now there's some text, albeit some rather ugly text, appended to your path.
The only real change I've made is the addition of this snippet:
vis.selectAll("text")
.data(groups)
.enter()
.append("text")
.attr("x", 8)
.attr("dy", 28)
.append("textPath")
.attr("xlink:href", function (d,i) { return "#path_" + i; })
.text(function (d,i) { return "path_" + i; });
You can see that you go through the usual selection and data binding. You then append your text with the attributes you want (definitely change the ones I borrowed from Mikes Bl.ock) and then you append the text path linking it to a path element in the xlink:href attribute. Obviously you then create some text. One of the cool things about textPath is that it allows you append curved paths.
I think that there's a bit of overkill using the groups as data for the textPath, so you might want to select a more appropriate data selection to bind to this.

Creating a dynamic list of DIVs with D3

I have been using D3 to create fancy animated charts, and the examples are great. However, I'm trying to do something seemingly a lot more basic, and having trouble - binding data to a simple list of DIVs.
I set up enter() to initialize elements at opacity 0, transition() to fade them in, and exit() to fade them out and remove them. enter() and exit() seem to be working fine - however, when an update contains an existing element already in the list, it seems to get partially removed - the containing DIV remains, but the contents disappear. I can't understand why the contents of the element would get changed in this way.
My code is as follows:
var data = [...];
sorted = data.sort(function(a, b) { return d3.descending(a.id, b.id); });
var tweet = tweetsBox
.selectAll('div')
.data(sorted, function(d) { return d.id; });
var enterDiv = tweet.enter()
.append("div")
.attr("class", "tweetdiv")
.style("opacity", 0);
enterDiv.append("div")
.attr("class", "username")
.text(function(d) { return "#" + d.username });
enterDiv.append("div")
.attr("class", "displayname")
.text(function(d) { return d.displayname });
enterDiv.append("div")
.attr("class", "date")
.text(function(d) { return d.date });
enterDiv.append("div")
.attr("class", "text")
.text(function(d) { return d.text });
tweet.transition()
.delay(200)
.style("opacity", 1);
tweet.exit()
.transition()
.duration(200)
.style("opacity", 0)
.remove();
I also set up a jsFiddle here demonstrating the issue.
The problem is that you're selecting the divs you created, but create more than one div per data element. When updating, d3 tries to match the data to the nested divs. As you're already assigning a special class to the top-level divs, the fix is very simple. Replace
.selectAll('div')
with
.selectAll('.tweetdiv')

Categories

Resources