d3: use anchor elements as chart labels - javascript

I am getting started with D3 and SVG but I haven't found anything clear on how to add hyperlinks. Here is some code I have to write labels to the left of the bars in a D3 bar chart. Is there a good sample somewhere to convert these labels to hyperlinks (say objects in rangeData had an href and name/label property)? I searched around a bit but haven't gotten much further than the svg spec for adding an anchor element.
chart.selectAll(".bar.barLabel")
.data(rangeData)
.enter().append("text")
.attr("class", "bar")
.attr("x", 0)
.attr("y", function (d, i) { return height(i) + barHeight(y, i) / 2; })
.attr("dx", -20)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(function (d) { return d.label; });

You can use the a element to achieve this, very similar to HTML itself. You wrap the content in the a element and provide the link target as the href attribute with xlink namespace.
chart.selectAll("a")
.data(rangeData)
.enter()
.append("a")
.attr("xlink:href", function(d) { return d.href; })
.append("text")
.text(function (d) { return d.label; });
Alternatively, you could use the foreignObject element to directly embed HTML into your SVG.

Related

d3 v6 add label to the Nodes

I want to add the id to the nodes of the graph in the example of
https://d3-graph-gallery.com/graph/network_basic.html
I tried
...
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
...
but the name does not appear
how can I add the name next to the node
The node variable represents a selection of SVG circles, which cannot contain text elements. You have to use a group element as a parent to hold the circle and the text elements.
First create a selection of group elements that the force simulation will place:
const nodes = svg
.selectAll("g")
.data(data.nodes)
.join("g");
Then add your circle and your text in the groups:
nodes.append("circle")
.attr("r", 20)
.style("fill", "#69b3a2")
nodes.append("text")
.attr("text-anchor", "middle") // text is centered in the circle
.attr("alignment-baseline", "middle")
.text(d => d.name);
Because the force simulation works on group elements, the ticked() function must be adapted to translate them:
nodes.attr("transform", d => `translate(${d.x+6},${d.y-6})`);
See example here: https://codepen.io/ccasenove/pen/eYKzmwd

D3 bar chart bar text labels not visible properly

I have a stacked bar chart in d3.js
For every stacked bar i have corresponding text value showing near stack itself.
problem is, some text values displaying are hidden behind bars, where as some are visible over bars. I want all text to visible over my bars. my code looks like,
bar.append("text")
.attr("x", function (d) { return x(d.x); })
.attr("y", function (d) { return y(d.y0 + d.y); })
.attr("dy", ".35em")
.attr('style', 'font-size:13px')
.text(function (d) { if (d.y != 0) { return "$" + d.y; } })
.style('fill', 'black');
Basically the issue related to z-index. But there is no z-index for SVG, so it can be fixed by reordering elements. Details here With JavaScript, can I change the Z index/layer of an SVG <g> element?
The simplest and fastest way:
To add .reverse() to the dataset.
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.cost")
.data(dataset.reverse())
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) { return colors[i]; });
The better way
To add different containers for bars and labels and put them in the right order in the DOM.
Try it http://jsfiddle.net/kashesandr/z90aywdj/

Adding label to the links in D3 force directed graph

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

links in d3.js forced directed graph

In this example, how can I make the text of each node to be a clickable link?
I tried something similar to this code, but the values were not clickable:
var links = text.append("a").attr("xlink:href", "http://www.google.com/");
// A copy of the text with a thick white stroke for legibility.
links.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
links.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
EDIT / SOLUTION: turns out the css had this attriubte: pointer-events: none;
I had to delete it and then use as Elijah suggested.
Don't use links, drop it and append directly to your text <g> and it should work.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; })
.on("click", function() {yourFunction(yourVar)})
.on("mouseover", function() {yourFunction2(yourVar)})
.on("mouseout", function() {yourFunction3(yourVar)})
;
Also, if you want to pass the bound data, you'd do that like this:
.on("click", function(d) {yourFunction(d.yourVar)}
Whereas if you want to pass the actual d object, you can do it like this:
.on("click", yourFunction}
In which case yourFunction(d,i) can then reference d.whatever from your bound data.

How do I add a title attribute to the nodes of my force-directed graph generated by d3?

Following a d3 demonstration (http://goo.gl/lN7Jo), I am trying to create a force-directed graph. I am trying to add a title attribute to my node elements created by doing this.
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
// here is how I try to add a title.
.attr("title", "my title")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
However, the nodes of my graph are not displaying a title attribute. What is the proper way to do so? Thank you.
In SVG title attributes are really elements that describe their parent, so you would have to follow the example you linked...
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.append("title")
.text("my text");
Add this code right below where you initialise your node. This will add some hard-code text as title to each node.
node.append("title")
.text("my text");
If you want to add name as title, do this;
node.append("title")
.text(function (d) {
return d.name;
})

Categories