How to add text labels on edges [duplicate] - javascript

I have created a force directed graph but I'm unable to add text to the links created.
How can I do so?
Following is my code link
I have used the following line to append the titles on the link's, but its not coming.
link.append("title")
.text(function (d) {
return d.value;
});
What am I doing wrong with this ?

This link contains the solution that you need.
The key point here is that "title" adds tooltip. For label, you must provide slightly more complex (but not overly complicated) code, like this one from the example from the link above:
// Append text to Link edges
var linkText = svgCanvas.selectAll(".gLink")
.data(force.links())
.append("text")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("x", function(d) {
if (d.target.x > d.source.x) {
return (d.source.x + (d.target.x - d.source.x)/2); }
else {
return (d.target.x + (d.source.x - d.target.x)/2); }
})
.attr("y", function(d) {
if (d.target.y > d.source.y) {
return (d.source.y + (d.target.y - d.source.y)/2); }
else {
return (d.target.y + (d.source.y - d.target.y)/2); }
})
.attr("fill", "Black")
.style("font", "normal 12px Arial")
.attr("dy", ".35em")
.text(function(d) { return d.linkName; });
The idea of the code is simple: It calculates the midpoint of the link, and displays some text at that place (you can decide what that text actually is). There are some additional calculations and conditions, you can figure it out from the code, however you'll anyway want to change them depending on your needs and aesthetics.
EDIT: Important note here is that "gLink" is the name of the class of links, previously defined with this code:
// Draw lines for Links between Nodes
var link = svgCanvas.selectAll(".gLink")
.data(force.links())
In your example, it may be different, you need to adjust the code.
Here is a guide how to incorporate solution from example above to another example of force layout that doesn't have link labels:
SVG Object Organization and Data Binding
In D3 force-directed layouts, layout must be supplied with array of nodes and links, and force.start() must be called. After that, visual elements may be created as requirements and desing say. In our case, following code initializes SVG "g" element for each link. This "g" element is supposed to contain a line that visually represent link, and the text that corresponds to that link as well.
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter()
.append("g")
.attr("class", "link")
.append("line")
.attr("class", "link-line")
.style("stroke-width", function (d) {
return Math.sqrt(d.value);
});
var linkText = svg.selectAll(".link")
.append("text")
.attr("class", "link-label")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Black")
.style("font", "normal 12px Arial")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
"g" elements have class "link", lines have class "link-line", ad labels have class "link-label". This is done so that "g" elements may be easily selected, and lines and labels can be styled in CSS file conveninetly via classes "link-line" and "link-label" (though such styling is not used in this example).
Initialization of positions of lines and text is not done here, since they will be updated duting animation anyway.
Force-directed Animation
In order for animation to be visible, "tick" function must contain code that determine position of lines and text:
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; });
linkText
.attr("x", function(d) {
return ((d.source.x + d.target.x)/2);
})
.attr("y", function(d) {
return ((d.source.y + d.target.y)/2);
});
Here is the resulting example: plunker

Related

Filter paths and append text

I would like to set a filter on paths and append text but nothing happens.
var filteredElements = svgContainer.selectAll("path")
//.data(feat.features)
.append("text")
.filter(function (d) {
if (d.properties.myID > 0) {
return true;
};
})
.attr("x", function (d) {
return path.centroid(d)[0];
})
.attr("y", function (d) {
return path.centroid(d)[1];
})
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo");
filteredElements contains 46 elements which are correct but the text is not being appended.
With that code, it works fine but I need the condition in my filter:
svgContainer.selectAll("path[PE='1442']")
.data(feat.features)
.enter().append("text")
.attr("x", function (d) {
return path.centroid(d)[0];
})
.attr("y", function (d) {
return path.centroid(d)[1];
})
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo");
I'm adding this as a second answer because there isn't enough room in a comment, but it suffices as an answer itself.
You have paths drawn on the svg, and you want to draw text for a subset of those paths.
There are two approaches that could be used for this. One is to use a parent g element to hold both path and text:
// Append a parent:
var g = svg.selectAll(null) // we want to enter an element for each item in the data array
.data(features)
.enter()
.append("g");
// Append the path
g.append("path")
.attr("d",path)
.attr("fill", function(d) { ... // etc.
// Append the text to a subset of the features:
g.filter(function(d) {
return d.properties.myID > 0; // filter based on the datum
})
.append("text")
.text(function(d) { .... // etc.
The bound data is passed to the children allowing you to filter the parent selection before adding the child text.
The other approach is closer to what you have done already, but you don't quite have idiomatic d3. We also don't need to re-bind the data to the paths (d3.selectAll("path").data(), instead we can use:
svgContainer.selectAll(null)
.data(feat.features.filter(function(d) { return d.properties.myID > 0; }))
.enter()
.append("text")
.attr("x", path.centroid(d)[0])
.attr("y", path.centroid(d)[1])
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo")
As an aside, your initial approach was problematic in that it:
it appends text to path elements directly, which won't render (as you note)
it is binding data to the paths again, for each element in the selection, you are binding an item of the data array to a selected element - since the selection is a sub-set of your paths, but your data is the full dataset, you are likely assigning different data to each path (without specifying an identifier, the ith item in the full dataset is bound to the ith element in the sub-selection).
I have now a solution, I think. My text nodes were inside my path nodes. Now I'm just doing this in my if condition and add my text node under my paths.
svgContainer.selectAll("path")
.data(feat.features)
.filter(function (d) {
if (d.properties.myID > 0) {
d3.select("svg")
.append("text")
.attr("x", path.centroid(d)[0])
.attr("y", path.centroid(d)[1])
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo")
};
})

D3 - Append SVG inside SVG

I have been trying to append a set of SVGs inside SVG. So, in inside SVG, I want to create a function to make plot. However, this doesn't work in the way I expected as the inside SVGs don't have the dimension according to my specification. So, I'd like to know what went wrong.
svg_g_g = svg_g.append("g")
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d) {
return "translate(" + xScale(d.key) + "," + lift + ")"
})
.append("svg")
.attr("width", function(d) { return xScale(d.key) })
.attr("height", height)
.append("line")
.style("stroke", "black")
.attr("x1", function(d) { return xScale(d.key) })
.attr("y1", height-100)
.attr("x2", function(d) { return xScale(d.key) + 50 } )
.attr("y2", height-100);
This is the output.
While if I bind data to g (without appending svg), the result looks more promising.
svg_g_g = svg_g.append("g");
svg_g_g.selectAll("line")
.data(data)
.enter()
.append("line")
.style("stroke", "black")
.attr("x1", function(d) { return xScale(d.key) })
.attr("y1", height-100)
.attr("x2", function(d) { return xScale(d.key) + 50 } )
.attr("y2", height-100);
and this is the result. (notice: the lines were shown in this case)
Any help will be appreciated.
edit: what I intended to do was I wanted to create a box-plot, I used "iris" dataset here as I can compared it against other data visualisation libraries. The current state I tried to create a SVG with an equal size for each category which I would use to contain box-plot. In other words, after I can create internal SVGs successfully, I will call a function to make the plot from there. Kinda same idea Mike did here.

n.call is not a function issue when doing a transition

I am trying to generate some text labels and to then transition them onto a D3 graph.
Pseudo code: (1) Generate text labels at coordinates 0,0
(2) Transition labels to desired [x,y]
When I run the script below, however, I get the following issue in the console log window:
My code is as follows:
svg.selectAll(".groups")
.data(sampleData)
.append("text")
.attr("class", "label")
.text(function(d){return d.c})
.attr("dx",0)
.attr("dy", 0)
.style("fill-opacity",0)
.each("end", function(){
d3.selectAll(".label")
.transition()
.duration(2000)
.style("fill-opacity", 1)
.attr("dx", function(d) {
return x(d.x);
})
.attr("dy", function(d) {
return y(d.y);
});
})
Have you any idea what is going wrong? The two bits of code are running just fine. It's the transition that is giving me the headache.
You don't need that each here. Each adds a listener to a transition, but you have no transition selection when you get to that each function:
svg.selectAll(".groups")
.data(sampleData)
.append("text")
.attr("class", "label")
.text(function(d) {
return d.c
})
.attr("dx", 0)
.attr("dy", 0)
.style("fill-opacity", 0)
.each("end", function() {...
//No 'transition()' before this point
(by the way, you also don't have an "enter" selection, since there is no enter in the code)
Thus, it can be just this: setting the positions to zero (which you don't need to do, because the positions are zero by default), and changing them in the transition selection. Here is the demo:
var svg = d3.select("svg");
var data = ["foo", "bar", "baz", "foobar", "foobaz", "barbaz"];
svg.selectAll("foo")
.data(data)
.enter()
.append("text")
.text(function(d) {
return d
})
.style("fill-opacity", 0)
.transition()
.duration(2000)
.style("fill-opacity", 1)
.attr("dx", function(){ return Math.random()*280})
.attr("dy", function(){ return 20 + Math.random()*130});
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Best solution to label nodes in SVG dynamic tree (using D3.js)

I am trying to modify this D3.js example (Dynamic Node-Link Tree) by adding a specific label (SVG text) to each node, but unsucessfully.
If I understand correctly, after a brief look at SVG specs and D3 documentation, the best way would be to create SVG groups and move them around.
Unfortunately, this is not working, as the transitions have no effect on the groups.
Is there a simple(r) way I am not aware of?
Many thanks.
If you're looking for an effect where you switch the circles for text labels, you can do the following:
// Enter any new nodes at the parent's previous position.
node.enter().append("svg:text")
.attr("class", "node")
.attr("x", function(d) { return d.parent.data.x0; })
.attr("y", function(d) { return d.parent.data.y0; })
.attr("text-anchor", "middle")
.text(function(d) { return "Node "+(nodeCount++); })
.transition()
.duration(duration)
.attr("x", x)
.attr("y", y);
See the fiddle here: http://jsfiddle.net/mccannf/pcwMa/4/
Edit
However, if you're looking to add labels alongside the circles, I would not recommend using svg:g in this case, because then you would have to use transforms to move the groups around. Instead, just double up on the circle nodes and text nodes like so in the update function:
// Update the nodes…
var cnode = vis.selectAll("circle.node")
.data(nodes, nodeId);
cnode.enter().append("svg:circle")
.attr("class", "node")
.attr("r", 3.5)
.attr("cx", function(d) { return d.parent.data.x0; })
.attr("cy", function(d) { return d.parent.data.y0; })
.transition()
.duration(duration)
.attr("cx", x)
.attr("cy", y);
var tnode = vis.selectAll("text.node")
.data(nodes, nodeId);
tnode.enter().append("svg:text")
.attr("class", "node")
.text(function(d) { return "Node "+(nodeCount++); })
.attr("x", function(d) { return d.parent.data.x0; })
.attr("y", function(d) { return d.parent.data.y0; })
.transition()
.duration(duration)
.attr("x", x)
.attr("y", y);
// Transition nodes to their new position.
cnode.transition()
.duration(duration)
.attr("cx", x)
.attr("cy", y);
tnode.transition()
.duration(duration)
.attr("x", x)
.attr("y", y)
.attr("dx", 4)
.attr("dy", 4); //padding-left and padding-top
A fiddle that demonstrates this can be found here: http://jsfiddle.net/mccannf/8ny7w/19/

How to put labels on the edges in the Dendrogram example?

Given a tree diagram like the Dendrogram example (source), how would one put labels on the edges? The JavaScript code to draw the edges looks like the next lines:
var link = vis.selectAll("path.link")
.data(cluster.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
Mike Bostock, the author of D3, very graciously helped with the following solution. Define a style for g.link; I just copied the style for g.node. Then I replaced the "var link =...." code with the following. The x and y functions place the label in the center of the path.
var linkg = vis.selectAll("g.link")
.data(cluster.links(nodes))
.enter().append("g")
.attr("class", "link");
linkg.append("path")
.attr("class", "link")
.attr("d", diagonal);
linkg.append("text")
.attr("x", function(d) { return (d.source.y + d.target.y) / 2; })
.attr("y", function(d) { return (d.source.x + d.target.x) / 2; })
.attr("text-anchor", "middle")
.text(function(d) {
return "edgeLabel";
});
The text function should ideally provide a label specifically for each edge. I populated an object with the names of my edges while preparing my data, so my text function looks like this:
.text(function(d) {
var key = d.source.name + ":" + d.target.name;
return edgeNames[key];
});

Categories

Resources