d3js v5 + Topojson v3 Map not rendering - javascript

I don't know why, according to the topojson version (may be) I have:
TypeError: t is undefined
An explanation could be nice! (I use the last version of topojson.)
Here an example of TypeError is undefined (pointing to topojson file)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/d3#5.0.0/dist/d3.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
</head>
<body>
<svg width="960" height="600"></svg>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var unemployment = d3.map();
var path = d3.geoPath();
var x = d3.scaleLinear()
.domain([1, 10])
.rangeRound([600, 860]);
var color = d3.scaleThreshold()
.domain(d3.range(2, 10))
.range(d3.schemeBlues[9]);
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0,40)");
g.selectAll("rect")
.data(color.range().map(function(d) {
d = color.invertExtent(d);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("fill", function(d) { return color(d[0]); });
g.append("text")
.attr("class", "caption")
.attr("x", x.range()[0])
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Unemployment rate");
g.call(d3.axisBottom(x)
.tickSize(13)
.tickFormat(function(x, i) { return i ? x : x + "%"; })
.tickValues(color.domain()))
.select(".domain")
.remove();
var files = ["https://d3js.org/us-10m.v1.json", "unemployment.tsv"];
var promises1 = d3.json("https://d3js.org/us-10m.v1.json");
var promises2 = d3.tsv("unemployment.tsv");
Promise.all([promises1, promises2]).then(function(us){
console.log(us[0]);
console.log(us[1]);
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us[0].objects.counties).features)
.enter().append("path")
.attr("fill", function(d) { return color(d.rate = unemployment.get(d.id)); })
.attr("d", path)
.append("title")
.text(function(d) { return d.rate + "%"; });
svg.append("path")
.datum(topojson.mesh(us, us[0].objects.states, function(a, b) { return a !== b; }))
.attr("class", "states")
.attr("d", path);
});
</script>
</body>
</html>
My code : https://plnkr.co/edit/EzcZMSEQVzCt4uoYCLIc?p=info
Original (d3js v4 + Topojson v2) : https://bl.ocks.org/mbostock/4060606
Here an another example of TypeError is undefined (pointing to topojson file)
My code : https://plnkr.co/edit/o1wQX3tvIDVxEbDtdVZP?p=preview

The two examples have two separate issues in relation to topojson.
In the first example you update where the topojson is held from us to us[0] due to the change in how files are fetched. However, you haven't quite updated the code to reflect this change:
In Original: .data(topojson.feature(us, us.objects.counties).features)
In Question: .data(topojson.feature(us, us[0].objects.counties).features)
And fixed: .data(topojson.feature(us[0], us[0].objects.counties).features)
Updated plunkr.
However, the issue in the second example is a little different.
topojson.feature requires two parameters, a topology and an object. The topology is the variable holding the json, which you have correct. However, the object is not arcs. The variable holding the topojson has a property called objects, and in that there will always be at least one property representing a feature collection (states, counties, etc). This object (or one of these objects) is what we want.
Here is a snippet of your topojson:
... "objects":{"dep_GEN_WGS84_UTF8":{"type":"GeometryCollection","geometries":[{"arcs ..."
We want topojson.feature(data,data.objects.dep_GEN_WGS84_UTF8).
If making topojson with tools such as mapshaper, the object we want to display is the same as the name of the file used to create it. Generally, a quick word search through the topojson for "object" will also get you to the proper object pretty quick.
The arcs property in a topojson is convenient storage for the pieces that make up the features, not the features themselves.
Updated plunkr.
In both cases the topology parameter passed to topojson.feature won't contain the specified features, generating the same error.

Related

Why mouserover returning all data in callback

I'm new to d3 and currently trying to make a simple line chart using the example provided by Mike Bostock, I have arrieved to the following code.
<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var parseTime = d3.timeParse("%d-%b-%y");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
d3.tsv("data.tsv", function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.select(".domain");
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Weight (lbs)");
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line)
.on("mouseover", handleMouseOver);
});
function handleMouseOver(d,i) {
console.log(d);
console.log(i);
}
</script>
taken from the following link, I append the link if you want to test with the sample data https://bl.ocks.org/mbostock/3883245
The thing is that I want to add a new feature where the user can hover over a part of the line and see what is the value of the data at that moment, what I understand is that I append a new path for each entry in the data, the problem is that when I add a callback to the mouseover event that is suppose to receive as a parameter the data being hover like this:
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line)
.on("mouseover", handleMouseOver);
function handleMouseOver(d,i) {
console.log(d);
console.log(i);
}
The console.log(d) shows all the data in the data array and not the specific entry in the array that is being hovered, also the index i always gives 0. I want to know what I'm doing wrong or how can I achieve this. Thanks in advance.
Take the following code for the last append (all else is unchanged; and in that block, I also only changed the lines ending with //!!:
g.append("g").selectAll("path").data(data.slice(0, data.length-1)).enter().append("path") //!!
//.datum(data) //!!
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", function(d,i){return line([data[i], data[i+1]])}) //!!
.on("mouseover", handleMouseOver);
This gives you the correct data and index on mouse over depending on the segment.
Let me dive into the background a little bit:
datum sets the whole data as input for the only instance of path (when checking the DOM in your code above or bl.ocks.org, you'll only see one <path> with an insanely long d. Which is nice, as the line() function can handle this perfectly well. However, you only have ONE element for mouseover which doesn't help
hence, I chose another approach with one path for each line segment: My code has an insane number of <path>s with a very simple d each. However, each path can have a separate mouseover
to not get overwhelmed, I enclosed all the paths in a g, which doesn't hurt anyway
I did use the data() function. You can read up here for details: https://github.com/d3/d3-selection#selection_data
in brief, I tell it to take a selection of all path elements currently under g (none), and append as many new paths as necessary to satisfy the data at hand. Then, for each path, apply the next lines
(this doesn't yet update from a new data, but I want to keep it short)
and finally, to make it sound, I had to slice the data for each input
(I didn't use ES6 syntax for simplicity now, though ES6 would look nicer and is shorter. Doesn't matter for the result, however)

Choropleth map returning undefined

I'm attempting a choropleth map of US Counties, and am essentially using Mike Bostock's example from here https://bl.ocks.org/mbostock/4060606 I am using education instead of unemployment, but otherwise it's the same. I'd like to add just one more piece to it and have the county name display along with the rate. However, when I call the county name, I get "undefined" returned. To be clear 'rate' returns just fine, 'county' shows up undefined. Can anyone help? Thanks!
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.counties {
fill: none;
/*stroke: black;*/
}
.states {
fill: none;
stroke: #fff;
stroke-linejoin: round;
}
</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var Bachelor = d3.map();
var path = d3.geoPath();
var x = d3.scaleLinear()
.domain([0, 70])
.rangeRound([600, 860]);
var color_domain = [10, 20, 30, 40, 50, 60, 70]
var ext_color_domain = [10, 20, 30, 40, 50, 60, 70]
var color = d3.scaleThreshold()
.domain(color_domain)
.range([" #85c1e9", "#5dade2", "#3498db", "#2e86c1", "#2874a6", " #21618c"," #1b4f72"]);
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0,40)");
g.selectAll("rect")
.data(color.range().map(function(d) {
d = color.invertExtent(d);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("fill", function(d) { return color(d[0]); });
g.append("text")
.attr("class", "caption")
.attr("x", x.range()[0])
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("% of Adults with Bachelor's or higher");
g.call(d3.axisBottom(x)
.tickSize(13)
.tickFormat(function(x, i) { return i ? x : x; })
.tickValues(color.domain()))
.select(".domain")
.remove();
d3.queue()
.defer(d3.json, "https://d3js.org/us-10m.v1.json")
.defer(d3.tsv, "Bachelor2.tsv", function(d) { Bachelor.set(d.id, d.rate, d.county); })
.await(ready);
function ready(error, us) {
if (error) throw error;
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("fill", function(d) { return color(d.rate = Bachelor.get(d.id)); })
.attr("d", path)
.append("title")
.text(function(d) { return (d.county +" " d.rate +"%"); });
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "states")
.attr("d", path);
}
</script>
There are two problems in your code.
The first problem in your code lies here:
Bachelor.set(d.id, d.rate, d.county);
In both javascript maps and D3 maps (which are slightly different), you cannot set two values for the same key. Therefore, the syntax has to be:
map.set(key, value)
Let's show it.
This works, setting the value "bar" to "foo":
var myMap = d3.map();
myMap.set("foo", "bar");
console.log(myMap.get("foo"))
<script src="https://d3js.org/d3.v4.min.js"></script>
However, this will not work:
var myMap = d3.map();
myMap.set("foo", "bar", "baz");
console.log(myMap.get("foo"))
<script src="https://d3js.org/d3.v4.min.js"></script>
As you can see, the value "baz" was not set.
That was assuming that country is a property in your Bachelor2.tsv file. And that brings us to the second problem:
In your paths, this is the data:
topojson.feature(us, us.objects.counties).features
If you look at your code, you set a property named rate (using your map) to that data...
.attr("fill", function(d) { return color(d.rate = Bachelor.get(d.id)); })
//you set 'rate' to the datum here --------^
...but you never set a property named country. Therefore, there is no such property for you to use in the callbacks.
As explained above, you cannot set it using the same map you used to set the rate. A solution is using an object instead. Alternatively, you could use two maps, which seems to be the fastest option.

d3.js: Confusion about the order in which the code is executed

I am trying to make an interactive bar chart in D3.js
I uploaded everything to github for easy reference. I also included index.html at the end of my question.
My starting point is data.json containing an array of 7 items (i.e. countries). Each country has an attribute 'name' and four other attributes. These represent the exposition of private banks and the state to Greek debt for the years 2009 and 2014.
My goal is to create a bar chart that starts by showing the exposition of each country's banks and public sector in 2009 (so two bars for each country) and that changes to the year 2014 once the user clicks on the appropriate button.
I had managed to make it all work nicely! However, I had to create manually separate lists for each (sub-)dataset I needed to use. For example I created one called y2009 which included the exposition of bank and state for country 1, then the same for country 2, an so on..
(I left one of the list and commented it out on line 43)
I wanted to make my code more flexible so I created a for loop that extracts the data and creates the lists for me. (see lines 46-60). This did not work because the for loops would start before the data was actually loaded. Hence I would end up with empty lists.
So I grouped the for loops into a function (prepare()) and executed that function within the function that loads the data (lines 18-30). This fixed that issue...
..and created a new one! The two functions that should set the scales (see lines 67-73) do not work because their calculations require on one of the lists created by the for loops (namely 'total').
(I assume this is due to the list being created after the scale methods are called.)
The curious thing is that if I run the script, then copy in the console the xScale and yScale functions, and then copy the draw function (lines 101-212) everything works.
Hence I tried to group everything into functions (e.g. setScales, draw) so that I would call them in the order I want at the end of the script (lines 214-215) but this creates problem because certain variables (e.g. xScale and yScale) need to be global.
I also tried to first create them in the global space and then modify them through setScales. This did not work either.
Summing up, wait I don't understand is:
In which order should I write the code to make things work(again)? Is it a good idea to wrap operations within functions (e.g. setting the scales, drawing bars and labels) and then calling the function in the right order?
Which type of object is created with the scale method? I am confused on whether they are actual functions.
I hope this was not too much of a pain to read and thank everyone who made it through!
Fede
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="d3.min.js"></script>
</head>
<body>
<p>Introductory text here!</p>
<p>
<button id="change2009"> 2009 </button>
<button id="change2014"> 2014 </button>
</p>
<div id="country"></div>
<script type="text/javascript">
d3.json("data.json", function(error, json) {
if (error) {
console.log(error);
} else{
console.log(json);
dataset=json;
}
prepare (dataset);
});
//load data
var dataset;
var bank09=[];
var state09=[];
var bank14=[];
var state14=[];
var y2009=[];
var y2014=[];
var total=[];
var xScale;
var yScale;
//var total = [4.76, 0, 0.12, 6.36, 4.21, 0, 0.04, 7.96, 78.82, 0, 1.81, 46.56, 45, 0, 13.51, 61.74, 6.86, 0, 1.06, 40.87, 12.21, 0, 1.22, 13.06, 1.21, 0, 0.39, 27.35];
function prepare (dataset){
for (i in dataset) {bank09.push(dataset[i].bank09);
state09.push(dataset[i].state09);
bank14.push(dataset[i].bank14);
state14.push(dataset[i].state14);
y2009.push(dataset[i].bank09);
y2009.push(dataset[i].state09);
y2014.push(dataset[i].bank14);
y2014.push(dataset[i].state14);
total.push(dataset[i].bank09);
total.push(dataset[i].state09);
total.push(dataset[i].bank14);
total.push(dataset[i].state14);
}
}
//overwrite dataset
dataset2=y2009;
//scales
function setScales () {
var xScale = d3.scale.ordinal()
.domain(d3.range(total.length/2))
.rangeRoundBands([0, w], 0.1);
var yScale = d3.scale.linear()
.domain([0, d3.max(total)])
.range([0, h]);
console.log(yScale(89));
}
//layout
var w = 600;
var h = 600;
var barPadding = 1;
//coountry names
var country = ["Austria", "Belgium", "France", "Germany", "Italy", "Holland", "Spain"];
d3.select("#country")
.data(country)
.enter()
.append("rect")
.attr("class", "country")
//.append("text")
//.text(function(d){
// return d;
// })
//draw svg
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
function draw () {
//draw bars
svg.selectAll("rect")
.data(dataset2)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d){
return h - yScale(d);
})
.attr("width", xScale.rangeBand)
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "black");
//add labels
svg.selectAll("text")
.data(dataset2)
.enter()
.append("text")
.text(function(d){
return d;
})
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "red")
.attr("x", function(d, i){
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
if (d<3) {
return h - 15;
} else {
return h - yScale(d) + 15;}
})
//interactivity
d3.select("#change2014")
.on("click", function() {
//update data
dataset2=y2014;
//update bars
svg.selectAll("rect")
.data(dataset2)
.transition()
.duration(3000)
.attr("y", function(d){
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
//update labels
svg.selectAll("text")
.data(dataset2)
.transition()
.duration(3000)
.text(function(d){
return d;
})
.attr("x", function(d, i){
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
if (d<3) {
return h - 15;
} else {
return h - yScale(d) + 15;}
})
})
d3.select("#change2009")
.on("click", function() {
//update data
dataset2=y2009;
//update bars
svg.selectAll("rect")
.data(dataset2)
.transition()
.duration(3000)
.attr("y", function(d){
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
//update labels
svg.selectAll("text")
.data(dataset2)
.transition()
.duration(3000)
.text(function(d){
return d;
})
.attr("x", function(d, i){
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
if (d<3) {
return h - 15;
} else {
return h - yScale(d) + 15;}
})
})
}
setScales ();
draw();
</script>
In which order should I write the code to make things work(again)? Is
it a good idea to wrap operations within functions (e.g. setting the
scales, drawing bars and labels) and then calling the function in the
right order?
As Lars pointed out, you can put everything inside the d3.json callback. This is because you only want to start rendering with D3 once you have the data. The d3.json method is asynchronous, which means that after you call d3.json(), the code afterwards will execute first before the function inside the d3.json method has finished. Check out http://rowanmanning.com/posts/javascript-for-beginners-async/ for more on asynchronous behavior in Javascript.
Given that you only want to start rendering when the d3.json method has completed, you could also just organize the other parts of your code into smaller functions and call some sort of initializer function from within the d3.json success callback, sort of like what you are doing with the prepare function. This is a cleaner approach and starts taking you towards a model-view paradigm.
Which type of object is created with the scale method? I am confused
on whether they are actual functions.
The scale method does return a function, but with additional functions added to its prototype. Try printing out "someScale.prototype" to see all of the various methods you can use. I'd also highly recommend Scott Murray's tutorial on D3. Here is the chapter on scales: http://alignedleft.com/tutorials/d3/scales

How to add Label to each state in d3.js (albersUsa)?

The us.json loaded, but when i try to add Label name i can't make it work. I don't see the name property in .json file so how can i add each state name? I'm really new to this framework.
I try different Tutorial on Google and Stackoverflow, but none of them work for me. Here is the link to couple tutorial i tried, that i think is worthy.
Add names of the states to a map in d3.js
State/County names in TopoJSON or go back GeoJSON?
The concerns I have:
I think I'm missing name property in us.json file. (if that's the issue, is there any other .json file that includes state name? And how to use the state name with that file?)
Is the US state name included in http://d3js.org/topojson.v1.min.js?
.html File (Framework Loaded)
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
.js File:
var width = 1500,
height = 1100,
centered;
var usData = ["json/us.json"];
var usDataText = ["json/us-states.json"];
var projection = d3.geo.albersUsa()
.scale(2000)
.translate([760, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.style("width", "100%")
.style("height", "100%");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
var g = svg.append("g");
d3.json(usData, function(unitedState) {
g.append("g")
.attr("class", "states-bundle")
.selectAll("path")
.data(topojson.feature(unitedState, unitedState.objects.states).features)
.enter()
.append("path")
.attr("d", path)
.attr("class", "states")
.on("click", clicked);
});
Thank you everyone in advanced. I also appreciate if you tell me where did you learn d3.js.
As you stated your us.json doesn't have state names in it. What it has, though, are unique ids and luckily, Mr. Bostock has mapped those ids to names here.
So, let's fix up this code a bit.
First, make the json requests to pull the data:
// path data
d3.json("us.json", function(unitedState) {
var data = topojson.feature(unitedState, unitedState.objects.states).features;
// our names
d3.tsv("us-state-names.tsv", function(tsv){
// extract just the names and Ids
var names = {};
tsv.forEach(function(d,i){
names[d.id] = d.name;
});
Now add our visualization:
// build paths
g.append("g")
.attr("class", "states-bundle")
.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "white")
.attr("class", "states");
// add state names
g.append("g")
.attr("class", "states-names")
.selectAll("text")
.data(data)
.enter()
.append("svg:text")
.text(function(d){
return names[d.id];
})
.attr("x", function(d){
return path.centroid(d)[0];
})
.attr("y", function(d){
return path.centroid(d)[1];
})
.attr("text-anchor","middle")
.attr('fill', 'white');
....
Here's a working example.

Fitting data for D3 graph to create legend

I have a data variable which contains the following:
[Object { score="2.8", word="Blue"}, Object { score="2.8", word="Red"}, Object { score="3.9", word="Green"}]
I'm interested in modifying a piece of a D3 graph http://bl.ocks.org/3887051 to display the legend, which would be the list of the "word", for my data set.
The legend script looks like this (from link above):
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
How do I modify their ageNames function to display the "word" set from my data? I'm not sure how they're utilizing the d3.keys. Is there another way to do it?
This should work more or less, but you may need to reverse() (as the original example does) or otherwise rearrange the elements of words, in order to correctly map a word to the right color. Depends on how you've implemented your graph.
var words = yourDataArray.map(function(entry) { return entry.word; });
var legend = svg.selectAll(".legend")
.data(words)
// The rest stays the same

Categories