Filter paths and append text - javascript

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")
};
})

Related

dot (symbol) color on d3.js multiline chart

I am trying to replicate this example of a multiline chart with dots. My data is basically the same, where I have an object with name and values in the first level, and then a couple of values in the second level inside values. For the most part, my code works, but for some reason, the j index in the anonymous function for the fill returns an array of repeated circle instead of returning the parent of the current element. I believe this may have something to do with the way I created the svg and selected the elements, but I can't figure it out. Below is an excerpt of my code that shows how I created the svg, the line path and the circles.
var svgb = d3.select("body")
.append("svg")
.attr("id","svg-b")
.attr("width", width)
.attr("height", height)
var gameb = svgb.selectAll(".gameb")
.data(games)
.enter()
.append("g")
.attr("class", "gameb");
gameb.append("path")
.attr("class", "line")
.attr("d", function(d) {return line_count(d.values); })
.style("stroke", function(d) { return color(d.name); })
.style("fill", "none");
gameb.selectAll("circle")
.data(function(d) {return d.values;})
.enter()
.append("circle")
.attr("cx", function(d) {return x(d.date);})
.attr("cy", function(d) {return y_count(d.count);})
.attr("r", 3)
.style("fill", function(d,i,j) {console.log(j)
return color(games[j].name);});
j (or more accurately, the third parameter) will always be the nodes in the selection (the array of circles here), not the parent. If you want the parent datum you can use:
.attr("fill", function() {
let parent = this.parentNode;
let datum = d3.select(parent).datum();
return color(datum.name);
})
Note that using ()=> instead of function() will change the this context and the above will not work.
However, rather than coloring each circle independently, you could use a or the parent g to color the circles too:
gameb.append("g")
.style("fill", function(d) { return color(d.name); })
.selectAll("circle")
.data(function(d) {return d.values;})
.enter()
.append("circle")
.attr("cx", function(d) {return x(d.date);})
.attr("cy", function(d) {return y_count(d.count);})
.attr("r", 3);
Here we add an intermediate g (though we could use the original parent with a few additional modifications), apply a fill color to it, and then the parent g will color the children circles for us. The datum is passed on to this new g behind the scenes.

First element in data getting rerendered rather than updated

Here is something similar to what is happening in my code : https://codepen.io/anon/pen/zJmvXa?editors=1010
Press the Update button to see the issue.
The problem in this codePen, is its only redrawing the first element (Myriel).
I think it must be around the enter,exit or the merge, but I don't fully grasp what's going on.
I thought the merge was to merge existing data with new, and the only data that should go into the enter should be the new data. And the exit is for removing redundant data?
As this graph has both circles and text, should the merge be made on the 'g' element that contains these ?
Perhaps it's to do with the data function :
.data(dataset1.nodes, function(d, i) {
return d;
});
If i change this to use d.id, it re renders everything again. I presume it's due to the data having an id attribute. How is this suppose to be done ?
// Apply the general update pattern to the nodes.
forceNetwork.node = d3
.select("#nodesContainer")
.selectAll("g.network-node")
.data(dataset1.nodes, function(d, i) {
return d
});
forceNetwork.node.exit().remove();
forceNetwork.nodeEnter = forceNetwork.node
.enter()
.append("g")
.attr("id", function(d, i) {
return "network-g-node-" + d.id;
})
.attr("class", function(d, i) {
return "network-node";
})
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
).merge(forceNetwork.node);
forceNetwork.nodeEnter
.append("circle")
.attr("id", function(d) {
return d.id;
})
.attr("class", "networkviewer-node")
.attr("fill", "red")
.attr("r", 20);
// Append images
forceNetwork.nodeEnter
.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.id });
The problem here is that you'er merging the update and enter selections...
forceNetwork.nodeEnter = forceNetwork.node
.enter()
.merge(forceNetwork.node);
... and, after that, appending the circles (and lines):
forceNetwork.nodeEnter
.append("circle")
That will necessarily duplicate the circles and lines.
Instead of that, merge the selection after appending the circles and lines to the enter selection, and also change the selection in your tick function.
Here is the refactored code: https://codepen.io/anon/pen/GXYozm?editors=1010

Why is label not getting added to all my paths?

Plunker: https://next.plnkr.co/edit/17t5ujwC71IK3PCi
Why is following not adding a "test" label to all my polygons?
/* NOT Working code */
groups.selectAll('.path_placeholder')
.enter()
.append('text')
.text("test")
Update
.enter() wasn't required as mentioned by Xavier. Removing it showed "test" for all nodes. But why then its not working when I do provide data and use enter() as following:
groups.selectAll('.path_placeholder')
.data(groupIds, function(d) {
return d;
})
.enter()
.append('text')
.text(function(d){
console.log(d);
return d;
})
I am trying to be able to show label for each of my polygon and for now just trying to add a dummy label to each of them.
Your problem here is the paths is a <path> selection, not a <g> one:
paths = groups.selectAll('.path_placeholder')
.data(groupIds, function(d) { return +d; })
.enter()
.append('g')
.attr('class', 'path_placeholder')
.append('path')//this makes the selection pointing to <path> elements
.attr('stroke', function(d) { return color(d); })
.attr('fill', function(d) { return color(d); })
.attr('opacity', 0);
Because of that, when you do...
groups.selectAll('.path_placeholder')
.data(groupIds, function(d) {
return d;
})
.enter()
//etc...
... your "enter" selection is empty, because you already have data associated to that paths selection.
Besides that, it makes little sense using a proper "enter" selection for the texts, since the data is the same data bound to the groups.
Solution: the solution here, which is the idiomatic D3 for this situation, is creating an actual <g> selection.
We can do that by breaking the paths selection, and giving it another name:
pathGroups = groups.selectAll('.path_placeholder')
.data(groupIds, function(d) {
return +d;
})
.enter()
.append('g')
.attr('class', 'path_placeholder');
Then you can just do:
paths = pathGroups.append('path')
.attr('stroke', function(d) {
return color(d);
})
.attr('fill', function(d) {
return color(d);
})
.attr('opacity', 0)
texts = pathGroups.append('text')
.text(function(d) {
return d;
});
Here is the forked Plunker: https://next.plnkr.co/edit/31ZPXIvSI287RLgO

How to add text labels on edges [duplicate]

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

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>

Categories

Resources