How to display names next to bubbles in d3js motion chart - javascript

In Mike Bostocks example http://bost.ocks.org/mike/nations/ there is so much data that putting the names of the countries there would make it chaotic, but for a smaller project I would like to display it.
I found this in the source:
var dot = svg.append("g")
.attr("class", "dots")
.selectAll(".dot")
.data(interpolateData(2004))
.enter().append("circle")
.attr("class", "dot")
.style("fill", function(d) { return color(d); })
.text(function(d) { return d.name; })
.call(position)
.sort(order);
dot.append("title")
.text(function(d) { return d.name; });
But somehow a title never shows up. Does anybody have an idea, how to display the name, next to the bubble?

As the other answer suggests, you need to group your elements together. In addition, you need to append a text element -- the title element only displays as a tooltip in SVG. The code you're looking for would look something like this.
var dot = svg.append("g")
.attr("class", "dots")
.selectAll(".dot")
.data(interpolateData(2004))
.enter()
.append("g")
.attr("class", "dot")
.call(position)
.sort(order);
dot.append("circle")
.style("fill", function(d) { return color(d); });
dot.append("text")
.attr("y", 10)
.text(function(d) { return d.name; });
In the call to position, you would need to set the transform attribute. You may have to adjust the coordinates of the text element.

Unfortunately grouping the text and circles together will not help in this case. The bubbles are moved by changing their position attributes (cx and cy), but elements do not have x and y positions to move. They can only be moved with a transform-translate. See: https://www.dashingd3js.com/svg-group-element-and-d3js
Your options here are:
1) rewrite the position function to calculate the position difference (change in x and change in y) between the elements current position and its new position and apply that to the . THIS WOULD BE VERY DIFFICULT.
or 2) Write a parallel set of instructions to setup and move the tags. Something like:
var tag = svg.append("g")
.attr("class", "tag")
.selectAll(".tag")
.data(interpolateData(2004))
.enter().append("text")
.attr("class", "tag")
.attr("text-anchor", "left")
.style("fill", function(d) { return color(d); })
.text(function(d) { return d.name; })
.call(tagposition)
.sort(order);
You will need a separate tagposition function since text needs 'x' and 'y' instead of 'cx', 'cy', and 'r' attributes. Don't forget to update the "displayYear" function to change the tag positions as well. You will probably want to offset the text from the bubbles, but making sure the text does not overlap is a much more complicated problem: http://bl.ocks.org/thudfactor/6688739
PS- I called them tags since 'label' already means something in that example.

you have to wrap the circle element and text together , it should look like
<country>
<circle ></circle>
<text></text>
</country>

Related

Hide negative part of line chart in d3.js

I have a d3.js line chart which may have negative values. My Y-span starts at 0 and goes up to the maximum value in the dataset. Thus, the line goes underneath the X-axis when there is a negative value.
This is fine, but what I need is to just hide the part of the line that is underneath the X-axis. I want to keep the values as they are, just use some CSS or JS to make the part of the line underneath the X-axis invisible.
I have tried with various overflow settings, but it doesn't seem to help. It is possible to make everything below the X-axis invisible by placing an element over that part, but then the X-axis labels are hidden too.
This is the code drawing the line:
x.domain([d3.min(data, function(d) { return d.date}), d3.max(data, function(d) { return d.date})]);
y.domain([0, 1.05 * d3.max(data, function (d) { return d.value; })]);
area.y0(y(0));
g.append("path")
.datum(data)
.attr("fill", "#f6f6f6")
.attr("d", area);
//create line
var valueline = d3.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.value); });
g.append("path")
.data([data])
.attr('fill', 'none')
.attr('stroke', '#068d46')
.attr("class", "line")
.attr("d", valueline);
Fiddle: https://jsfiddle.net/c1bvrd50/1/
One way to solve this problem is to clip the line inside a rectangle covering the positive values area. In SVG, this is done with clip-path.
This happens in two steps:
Define a rect inside clipPath, covering the chart area only:
g.append('clipPath')
.attr('id', 'clipRect')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height)
Clip the line path, using clip-path attribute:
g.append("path")
.data([data])
/* ... */
.attr("d", valueline)
.attr('clip-path', 'url("#clipRect")')
Updated jsFiddle implementing the solution: here.
What is left to do is update the tooltip's mousemove event listener in order not to display the tooltip whenever the value is lower than 0.
Recommendation as P.S.: Whatever the use case of the chart is, it is most likely desirable to show the portions of the chart with negative values. Therefore, the chart's y axis should cover values lower than 0, rather than omitting these.

fading out text label as well as nodes in d3

I have a filter function which fades out the rest of the nodes and highlights the selected set of nodes. I also want the labels associated to the nodes to reflect the same, i.e. fade out for the rest and only show the ones that are associated to the selected nodes. I have the following snippets:
// define properties of nodes
var node = g.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "dataNodes")
.attr('id', function(d){ return 'id' + d.id; });
// define visual properties of node labels
var text = g.append("g")
.attr("class", "labels")
.selectAll("text")
.data(graph.nodes)
.enter().append("text")
.attr("font-size","6px")
.attr("dx", 6)
.attr('id', function(d){ return 'id' + d.id; })
.attr("dy", ".15em")
.text(function(d) {
return d.name;
});
function filterByName(relevantArray){
d3.selectAll(".dataNodes").transition().duration(toggleTime).style("opacity", 0.3);
d3.selectAll(".labels").transition().duration(toggleTime).style("opacity", 0.3);
d3.selectAll(relevantArray).transition().duration(toggleTime).style("opacity", 1);
}
The filter function is passed with a set of IDs which is used for setting the opacity of the nodes and labels. Since the ID of both the node and associated label is the same, why is only the node's properties getting affected by the function and not the label?
You just answered your own question here:
Since the ID of both the node and associated label is the same,...
IDs are unique. You cannot have two elements with the same ID.
Thus, set different IDs for the texts...
.attr('id', function(d){ return 'idCircle' + d.id; })
And for the circles...
.attr('id', function(d){ return 'idLabel' + d.id; })
However, in your case, to select both the circle and the text later, you can simply use class instead:
.attr('class', function(d){ return 'class' + d.id; })
Because, unlike IDs, you can have two elements with the same class and, therefore, you can use selectAll to select all of them:
d3.selectAll(".someClass")
.transition()
//etc

How to get a subselection of a D3.js selection

I am trying to get a subselection of a given D3.js selection.
This part of the code creates the paths:
pieces.paths = pieces.groups
.append("path")
.attr("fill", function (d) { return d.data.color; });
Then, I set de "d" attribute:
pieces.paths
.attr("d", arc);
Working perfect. But pieces.paths has 3 elements, and I want to set the class of the first two elements to "highest". How may I do that?
selection.filter() is one option:
pieces.paths
.filter(function(d, i) {return i<2;})
.attr("class", "highest");

D3 circle pack - Adding labels to nodes

While I've seen this question asked a few times, I'm having a bit trouble implementing. What I'd like to do is have the label attribute centered within each circle (as mentioned here). I believe I'd be adding the text attribute to:
canvas.selectAll('circles')
.data(nodes)
.enter()
.append('svg:circle')
.attr('cx', function (d) {
return d.x;
})
.attr('cy', function (d) {
return d.y;
})
.attr('r', function (d) {
return d.r;
})
.attr('fill', function (d) {
return d.color;
});
But am confused on why the instructions they gave in the previous example I linked to doesn't work with the setup I currently have. I believe it's the pack option that could be throwing me off (about the difference between the two), but any further examples would be a huge help. Thanks!
Update
Thanks for the answers/suggestions, I updated the Codepen with my progress (as I needed two lines of data; should have clarified) which seems to be working well. Now this is packing into a circle - at the end of the day, I'd love for this to be packed in the actual #canvas width/height (which is a rectangle). I saw this treemap example - would that be what I'm going for here?
Demo of what I have so far
Perhaps the confusion is that you can't add labels to the circle selection (because in SVG, a circle element can't contain a text element). You need to either make a g element that contains both circle and text, or a separate selection for the text, e.g.:
canvas.selectAll('text')
.data(nodes)
.enter()
.append('svg:text')
.attr('x', function (d) {
return d.x;
})
.attr('y', function (d) {
return d.y;
})
// sets the horizontal alignment to the middle
.attr('text-anchor', "middle")
// sets the vertical alignment to the middle of the line
.attr('dy', '0.35em')
.text(function(d) {
return d.label;
});
See the updated demo: http://codepen.io/anon/pen/djebv

adding labels to node in d3.js

I am a newbie in d3.js
I am trying to add labels to my nodes.
But whatever I tried is not working..
My code is here:
http://jsfiddle.net/Ymtg5/1/
Its a mash up between http://bl.ocks.org/christophermanning/4208494
and force directed graphs.
Basically I am reading a json file and creating the said graph.
Now I want to add labels to node exactly like http://bl.ocks.org/mbostock/950642
I tried adding these lines
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
But its not working.
Any help. suggestions..
Thanks
Most probably the problem is that your JSON classes don't have a "name".
Right, this was not the problem
The relevant part of your code is as follows:
var node = svg.selectAll("path.node")
.data(nodes)
.enter().append("path").attr("class", "node")
.style("fill", function(d) { return fill(d.value); })
.style("stroke", function(d) { return d3.rgb(fill(d.value)).darker(); })
.call(force.drag);
// HERE should go node manipulation to add the text
force
.nodes(nodes)
.links(links)
.on("tick", tick)
.start();
function tick() {
//node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; );
node.attr("d", function(d) { return clip({"type":"F {"type":"Point","coordin...
link.attr("d", function(d) { return clip({"type":"Feature","geometry":{ ...
I have inserted a comment line where your node manipulation should go, if you want to add labels to the nodes. You are doing that inside the tick function (well, I think you are trying to do it there, the code isn't in the fiddle), and that function should be only for manipulation of the attr of the nodes. The place to create the text and append it to the node is outside of the function.

Categories