Random loading of labels for cities - javascript

I have a world map with the states of Germany and Syria and their cities. Right now they load totally randomly as you can see.
German cities are loaded partially because the labels are missing
The Syrian cities are not loaded at all. When I reload it radomly becomes one of the the pictures i posted.
This is my function for calling germany for example.
d3.json("germany.topo.json", function(error, ger){
if (error) throw error;
var states = topojson.feature(ger, ger.objects.states_germany),
cities = topojson.feature(ger, ger.objects.cities_germany);
g.selectAll(".states")
.data(states.features)
.enter()
.append("path")
.attr("class", "state")
.attr("class", function(d) { return "state " + d.id; })
.attr("d", path);
g.append("path")
.datum(cities)
.attr("d", path.pointRadius('0.35'))
.attr("class", "city");
g.selectAll(".place-label")
.data(cities.features)
.enter().append("text")
.attr("class", "place-label")
.attr("transform", function(d) { return "translate(" + projection(d.geometry.coordinates) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.properties.name; });
});
The date ist here
I can partially reproduce this error. Maybe you can take a look and tell me why it is not working properly.
Thanks in advance

The problem you're having is a result of this call, and the fact that you are repeating it for both the German and Syrian cities:
g.selectAll(".place-label")
.data(cities.features)
.enter().append("text")
.attr("class", "place-label")
.attr("transform", function(d) { return "translate(" + projection(d.geometry.coordinates) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.properties.name; });
You are messing up your selections by selecting all objects with class "place-label" in different calls to d3.json. Instead, try something like the following:
// For German cities
g.selectAll(".german-place-label")
// For Syrian cities
g.selectAll(".syrian-place-label")
This seems to fix your problem, though you might consider rewriting your code so you only need to add all the cities with one call, instead of two separate, nearly identical calls.

Related

My recursive function is too fast, to animate paths

I'm visualising voyages on a map with D3.js' path. My data is in a JSON file like the following format:
[{"begin_date":1519,"trips":[[-13.821772,14.294839],[-9.517688,-7.958521],[0.598434,-34.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]}]
As can be seen, sometimes there are multiple voyages for a year. The following recursive function works:
d3.json("data/output.json", function(error, trips) {
if (error) throw error
var nest = d3.nest()
.key(function(d){
return d.begin_date;
})
.entries(trips)
var trip = svg.selectAll(".voyage");
// Add the year label; the value is set on transition.
var label = svg.append("text")
.attr("class", "year label")
.attr("text-anchor", "end")
.attr("y", height - 400)
.attr("x", width+150)
.text(function(d) {return d});
var pnt = 0;
doTransition();
function doTransition() {
trip.data(nest[pnt].values).enter()
.append("path")
.attr("class", "voyage")
.style("stroke", colorTrips)
.attr('d', function(d) {label.text(d.begin_date); return lineGen(d.trips.map(reversed).map(projection))})
.call(function transition(path) {
path.transition()
.duration(500)
.attrTween("stroke-dasharray", tweenDash)
.each("end", function(d) {
d3.selectAll(".voyage")
.remove()
pnt++;
if (pnt >= nest.length){return;}
doTransition();
})
})
}
Some voyages plot as they should
However some of them, are never plotted (I can see in the log) and it jumps from year 1545-1569 despite there being data points in between. I suspect it is due to the recursive function calling itself before the transition is finished. But I am also not sure, in the slightest.
Hope it is sufficient, I am new to D3.js, and suddenly found myself out of depth.

D3 exit mutli-series line chart labels on transition

I'm trying to create a multi-series line chart (based off the Mike Bostock example) but transitioning between multiple data sets. I have gotten the lines to transition in and out, but the labels for each line stick around after they should have disappeared. Screenshot at this link.
Furthermore, the lines are transitioning in an odd way; almost like they are just extending the same line to create a new one (Second screenshot at this link).
Here is the relevant part of my code (where I draw the lines and add labels):
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d.candidate); });
var person = svg_multi.selectAll(".candidate")
.data(people);
var personGroups = person.enter()
.append("g")
.attr("class", "candidate");
person
.enter().append("g")
.attr("class", "candidate");
personGroups.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
var personUpdate = d3.transition(person);
personUpdate.select("path")
.transition()
.duration(1000)
.attr("d", function(d) {
return line(d.values);
});
person
.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.Date) + "," + y(d.value.candidate) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
person.selectAll("text").transition()
.attr("transform", function(d) { return "translate(" + x(d.value.Date) + "," + y(d.value.candidate) + ")"; });
person.exit().remove();
You are appending a new text element to each person every time you render and not removing the old ones. Presumably the code you posted gets run every time you want to draw the chart with new data, so you end up with more text elements every time, rather than updating the existing ones. You need to only append on the "enter" selection. You did this right on the path elements, so you just need to make the text work more like the path. I've updated your example with comments to highlight what I changed.
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d.candidate); });
var person = svg_multi.selectAll(".candidate")
// I added a key function here to make sure you always update the same
// line for every person. This ensures that when you re draw with different
// data, the line for Trump doesn't become the line for Sanders, for example.
.data(people, function(d) { return d.name});
var personGroups = person.enter()
.append("g")
.attr("class", "candidate");
// This isn't needed. The path and text get appended to the group above,
// so this one just sits empty and clutters the DOM
// person
// .enter().append("g")
// .attr("class", "candidate");
personGroups.append("path")
.attr("class", "line")
// You do this down below, so no need to duplicate it here
// .attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
// Append the text element to only new groups in the enter selection
personGroups.append("text")
// Set any static attributes here that don't update on data
.attr("x", 3)
.attr("dy", ".35em");
var personUpdate = d3.transition(person);
personUpdate.select("path")
.transition()
.duration(1000)
.attr("d", function(d) {
return line(d.values);
});
person.select("text")
// You don't have to do this datum call because the text element will have
// the same data as its parent, but it does make it easier to get to the last
// value in the list, so you can do it if you want
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.Date) + "," + y(d.value.candidate) + ")"; })
.text(function(d) { return d.name; });
// Remove this. You don't need it anymore since you are updating the text above
// person.selectAll("text").transition()
// .attr("transform", function(d) { return "translate(" + x(d.value.Date) + "," + y(d.value.candidate) + ")"; });
person.exit().remove();
The key to your question was really just doing personGroups.append('text') rather than person.append('text'). The rest was just me going overboard and pointing out some other ways to improve your code that should make it easier to understand and maintain.

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

Update line order (z-orientation) on mouseover in d3

I am new to using d3 and JavaScript and would appreciate some constructive feedback. I'm mocking up a practice example to learn d3 that involves plotting climate data (temperature anomaly) from 1880-2010 from two sources (GISS and HAD). So far I have generated a multiple line chart in d3 using this data. Code and data are here https://gist.github.com/natemiller/0c3659e0e6a0b77dabb0
In this example the data are originally plotted grey, but each line colored a different color on mouseover.
I would like to add two additional features.
I would like, on mouseover, to reorder the lines so that the moused-over line is on top, essentially reorder the lines. I've read that this requires essentially replotting the SVG and I have tried code along the lines of this
source.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", "lightgrey")
.on("mouseover", function() {
if (active) active.classed("highlight", false);
active = d3.select(this.parentNode.appendChild(this))
.classed("highlight", true);
})
.style("stroke",function(d) {return color(d.name);})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.attr("id", function(d, i) { return "path-" + d.name; });
where the .on("mouseover"... code is meant to highlight the current "moused-over" line. It doesn't seem to work in my example. All the lines are highlighted initially and then turn grey with the mouseover/mouseout. If someone could help me identify how to update my code so that I can reorder the lines on mouseover that would be great!
I have been playing around with labeling the lines such that when either the line or its label is moused-over the line and label colors update. I've played around a bit using id's but so far I can't get both the text and the line to change color. I've managed to 1. mouseover the line and change the color of the text, 2. mouseover the text and change the color of the line, 2. mouseover the line and change the line, but not have both the line and the text change color when either of them are moused-over. Here is a section of code that serves as a start (using ids), but doesn't quite work as it only specifies the path, but not the text and the path. I've tried adding them both to d3.select('#path-','#text-'..., and variations on this, but it doesn't seem to work.
source.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", "lightgrey")
.on("mouseover", function(d){
d3.select(this)
.style("stroke",function(d) {return color(d.name);});
})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.attr("id", function(d, i) { return "path-" + d.name; });
source.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 15]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
.attr("x", 5)
.attr("dy", ".35em")
.style("stroke", "lightgrey")
.on("mouseover", function(d){
d3.select('#path-' + d.name)
.style("stroke",function(d) {return color(d.name);});
})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.text(function(d) { return d.name; })
.attr("font-family","sans-serif")
.attr("font-size","11px")
.attr("id", function(d, i) { return "text-" + d.name; });
I greatly appreciate your help. I am new to d3 and this help-serve. Its a steep learning curve at the moment, but I hope this example and the code is reasonably clear. If its not let me know how I can make it better and I can repost the question.
Thanks so much,
Nate
Chris Viau provided a good answer to this question over on the d3 Google group.
https://groups.google.com/forum/?fromgroups=#!topic/d3-js/-Ra66rqHGk4
The trick is to select the path's g parent to reorder it with the others:
this.parentNode.parentNode.appendChild(this.parentNode);
This appends the current selection's container "g" on top of all the other "g".
I've found this useful in lots of other instances as well.
Thanks Chris!

Overlay circle, text, etc. over d3.js multi-series lines

I have the multi series line chart code with slight modifications to support my data set. This is what I wish to do, and no solution I have looked at seems to function properly for me. I wish to overlay some element (circle, rectange, hidden, whichever) over each point on the line such that I could then attach a mouseover element on that point to display a box with data containing the d.time, d.jobID and how much that differs from an average. If possible, I would like the solution to only do this to the main line (the varying line) rather than the two lines drawn to represent the average. Here, I have a picture of the graph as-is for visual inspection. If that doesn't work, I have also attached it.
I have posted a bit the code below:
d3.tsv("values.tsv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "time" && key !== "jobID"; }));
data.forEach(function(d) {
d.time = parseDate(d.time);
d.jobID = parseInt(d.jobID);
});
var points = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {time: d.time, jobID: d.jobID, value: parseFloat(d[name],10)};
})
};
});
....
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 7)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("mbps");
var point = svg.selectAll(".point")
.data(points)
.enter().append("g")
.attr("class", "point");
point.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
point.append("text")
.datum(function(d) { return {name: d.name, jobID: d.jobID, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.time) + "," + y(d.value.value) + ")"; })
.attr("x", 6)
.attr("dy", ".7em")
.text(function(d) { return d.name; });
});
I have already tried the following code just to see if it worked with my implementation:
point.append("svg:circle")
.attr("stroke", "black")
.attr("fill", function(d, i) { return "black" })
.attr("cx", function(d, i) { return x(d.time) })
.attr("cy", function(d, i) { return y(d.value) })
.attr("r", function(d, i) { return 3 });
D3.JS seems like a pretty awesome piece of work, and I'm fortunate to have it.
EDIT: jsfiddle
The trick is to pass the data again to a selection and then operate on the result of that. Have a look at Mike's tutorial for some background and examples.
I've changed your jsfiddle to add circles here. Attaching svg:title elements or doing something else to show more information should be straightforward. Note that I modified your code to create the data points slightly to include the name with each element. This way, only one additional level of selections is necessary (treat all the points the same and add them in a single pass). The cleaner way to solve this from a code design point of view would be to have 2 additional levels -- first have a selection for the points for an individual line (and add an svg:g element to group them) and then add the points within this group. This would make the code quite a bit more complex and difficult to understand though.

Categories