I'm trying to make a map exactly like this example ( http://bost.ocks.org/mike/map/ ) except focused on Australia and New Zealand.
I've followed the instructions but the dots for the places don't render on my map.
This is how I'm generating my data:
ogr2ogr -f GeoJSON -where "adm0_a3 IN ('AUS', 'NZL')" subunits.json ne_10m_admin_0_map_subunits.shp
ogr2ogr -f GeoJSON -where "(iso_a2 = 'AU' OR iso_a2 = 'NZ') AND SCALERANK < 8" places.json ne_10m_populated_places.shp
topojson --id-property su_a3 -p name=NAME -p name -o aus.json subunits.json places.json
Here is the code I've got so far: http://bashsolutions.com.au/australia.html
The map shows up but the dots for the cities are not displaying. What am I doing wrong?
EDIT: So this isn't very clear just with the big long error so here's the actual code:
<script>
var width = 960,
height = 1160;
//var subunits = topojson.object(aus, aus.objects.subunitsAUS);
var projection = d3.geo.mercator()
//.center([0,0])
.center([180,-40])
.scale(400)
//.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection)
.pointRadius(2);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("aus.json", function(error, aus) {
svg.selectAll(".subunit")
.data(topojson.object(aus, aus.objects.subunits).geometries)
.enter().append("path")
.attr("class", function(d) { return "subunit " + d.id; })
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(aus, aus.objects.subunits, function(a,b) { return a !== b; }))
.attr("d", path)
.attr("class", "subunit-boundary");
svg.append("path")
.datum(topojson.mesh(aus, aus.objects.subunits, function(a,b) { return a == b; }))
.attr("d", path)
.attr("class", "subunit-boundary External");
/* This is the failing bit */
svg.append("path")
.datum(topojson.object(aus, aus.objects.places))
.attr("class", "place")
.attr("d", path);
/* End of failing bit */
/*
svg.selectAll(".place-label")
.data(topojson.object(aus, aus.objects.places).geometries)
.enter().append("text")
.attr("class", "place-label")
.attr("transform", function(d) { return "translate(" + projection(d.coordinates) + ")"; })
.attr("x", function(d) { return d.coordinates[0] > -1 ? 6 : -6; })
.attr("dy", ".35em")
.style("text-anchor", function(d) { return d.coordinates[0] > -1 ? "start" : "end"; })
.text(function(d) { return d.properties.name; });
*/
});
When you plot the outline you need to remove the TKL (Tokelau) data points.
svg.append("path")
.datum(topojson.mesh(aus, aus.objects.subunits, function(a, b) {
return a === b && a.id !=="TKL" }))
.attr("d", path)
.attr("class", "subunit-boundary External");
I'm still researching why this creates the error, but adding that condition to the mesh function filter seems to fix things.
I found away around this issue that solves the problem but it still doesn't explain why it was failing in the first place.
Here is the fix: http://bashsolutions.com.au/australia2.html
This chunk of code replaces the failing bit above:
svg.selectAll(".place")
.data(topojson.object(aus, aus.objects.places).geometries)
.enter().append("circle")
.attr("d", path)
.attr("transform", function(d) { return "translate(" + projection(d.coordinates) + ")"; })
.attr("r", 2)
.attr("class", "place");
So this gets around it by doing something similar to the labels bit (which is commented out above) but drawing a circle instead of text.
But I'm still not sure what was wrong with the above bit considering it's the same as Mike Bostock's example (apart from the data).
Related
I'm building a dashboard with a couple of d3 visualizations, which looks like:
The way I built this is by making a few div's on the page, and call the .js script inside these divs. This worked perfectly fine so far. Unfortunately I run into a problem when calling my .js file with a line graph on the right top div on my page. When I call the graph.js file, this happens:
I'm not entirely sure what's happening, but I think both the visualizations are using "path" elements, and therefore they interfere with eachother. This is the main code for the map of Europe:
//Load in GeoJSON data
d3.json("ne_50m_admin_0_countries_simplified.json", function(json) {
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.filter(function(d) { return d.properties.continent == 'Europe'}) //we only want Europe to be shown ánd loaded.
.append("path")
.attr("class", "border")
.attr("d", path)
.attr("stroke", "black")
.attr("fill", "#ADD8E6")
.attr("countryName", function(d){return d.properties.sovereignt})
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(d.properties.sovereignt + ', ' + getCountryTempByYear(dataset, d.properties.sovereignt, document.getElementById("selectYear").value))
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
})
.on("click", function(d){
//add/delete country to/from selected countries
updateSelectedCountries(d.properties.sovereignt);
//draw the temperature visualizations again
redrawTemp(getCountryTempByYear(dataset, selectedCountries[0], document.getElementById("selectYear").value), getCountryTempByYear(dataset, selectedCountries[1], document.getElementById("selectYear").value));
//update header from the webpage
d3.select("#header").text("Climate Change: 1840-2013. Currently viewing: " + selectedCountries + ", " + document.getElementById("selectYear").value + '.');
console.log(selectedCountries);
});
});
And this is the code for the line graph:
// set the dimensions and margins of the grap
var array = [[1850, 11.1], [1851, 11.7], [1852, 12.2], [1853, 11.1], [1854, 11.7], [1855, 12.2], [1856, 13.4]]
var array2 = [[1850, 14.1], [1851, 17.7], [1852, 22.2], [1853, 13.1], [1854, 24.7], [1855, 19.2], [1856, 13.4]]
// set the ranges
var x = d3.scaleLinear().range([0, 200]);
var y = d3.scaleLinear().range([200, 0]);
// define the line
var valueline = d3.line()
.x(function(d, i) { return x(array[i][0]); })
.y(function(d, i) { return y(array[i][1]); })
.curve(d3.curveMonotoneX); //smooth line
var valueline2 = d3.line()
.x(function(d, i) { return x(array2[i][0]); })
.y(function(d, i) { return y(array2[i][1]); })
.curve(d3.curveMonotoneX); //smooth line
var svg = d3.select("#div2")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.attr("id", "graph");
x.domain([1850, 1856]);
y.domain([10, 25]);
array.forEach(function(data, i){
svg.append("path")
.data([array])
.attr("class", "line")
.attr("d", valueline);
})
array2.forEach(function(data, i){
svg.append("path")
.data([array2])
.attr("class", "line")
.attr("d", valueline2);
})
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + 200 + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
As I said, I'm not entirely sure it's because of the graphs both using the "path" element, it could be something different too. Now what I'm wondering is: what is interfering with eachother? And how can I prevent this?
I can imagine something like a filter needs to be applied, but I'm not sure how to apply this to the right "path" elements.
Any help is highly appreciated!
When you create a new chart you should create a new variable to associate with it.
In your case, this might be happening due to the reuse of the variable var svg =....
Create one variable for each chart should be enough.
I am plotting points on a UK map using D3 off a live data stream. When the data points exceed 10,000 the browser becomes sluggish and the animation is no longer smooth. So I modify the dataPoints array to keep only the last 5000 points.
However when I modify the dataPoints the first time using splice() D3 stops rendering any new points. The old points gradually disappear (due to a transition) but there are no new points. I am not sure what I am doing wrong here.
I have simulated the problem by loading data of a CSV as well storing it in memory and plotting them at a rate of 1 point every 100ms. Once the number of dots goes above 10 I splice to retain the last 5 points. I see the same behaviour. Can someone review the code and let me know what I am doing wrong?
Setup and the plotting function:
var width = 960,
height = 1160;
var dataPoints = []
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height);
var projection = d3.geo.albers()
.center([0, 55.4])
.rotate([4.4, 0])
.parallels([40, 70])
.scale(5000)
.translate([width / 2, height / 2]);
function renderPoints() {
var points = svg.selectAll("circle")
.data(dataPoints)
points.enter()
.append("circle")
.attr("cx", function (d) {
prj = projection([d.longitude, d.latitude])
return prj[0];
})
.attr("cy", function (d) {
prj = projection([d.longitude, d.latitude])
return prj[1];
})
.attr("r", "4px")
.attr("fill", "blue")
.attr("fill-opacity", ".4")
.transition()
.delay(5000)
.attr("r", "0px")
}
/* JavaScript goes here. */
d3.json("uk.json", function(error, uk) {
if (error) return console.error(error);
console.log(uk);
var subunits = topojson.feature(uk, uk.objects.subunits);
var path = d3.geo.path()
.projection(projection);
svg.selectAll(".subunit")
.data(subunits.features)
.enter().append("path")
.attr("class", function(d) { return "subunit " + d.id })
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(uk, uk.objects.subunits, function(a,b) {return a!== b && a.id !== 'IRL';}))
.attr("d", path)
.attr("class", "subunit-boundary")
svg.append("path")
.datum(topojson.mesh(uk, uk.objects.subunits, function(a,b) {return a=== b && a.id === 'IRL';}))
.attr("d", path)
.attr("class", "subunit-boundary IRL")
svg.selectAll(".place-label")
.attr("x", function(d) { return d.geometry.coordinates[0] > -1 ? 6 : -6; })
.style("text-anchor", function(d) { return d.geometry.coordinates[0] > -1 ? "start": "end"; });
svg.selectAll(".subunit-label")
.data(topojson.feature(uk, uk.objects.subunits).features)
.enter().append("text")
.attr("class", function(d) { return "subunit-label " + d.id })
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.properties.name; })
// function applyProjection(d) {
// console.log(d);
// prj = projection(d)
// console.log(prj);
// return prj;
// }
lon = -4.6
lat = 55.45
dataPoints.push([lon,lat])
renderPoints()
});
Function to cleanup old points
var cleanupDataPoints = function() {
num_of_elements = dataPoints.length
console.log("Pre:" + num_of_elements)
if(num_of_elements > 10) {
dataPoints = dataPoints.splice(-5, 5)
}
console.log("Post:" + dataPoints.length)
}
Loading data from CSV and plotting at a throttled rate
var bufferedData = null
var ptr = 0
var renderNext = function() {
d = bufferedData[ptr]
console.log(d)
dataPoints.push(d)
ptr++;
renderPoints()
cleanupDataPoints()
if(ptr < bufferedData.length)
setTimeout(renderNext, 100)
}
d3.csv('test.csv', function (error, data) {
bufferedData = data
console.log(data)
setTimeout(renderNext, 100)
})
In the lines
points = svg.selectAll("circle")
.data(dataPoints)
points.enter() (...)
d3 maps each element in dataPoints (indexed from 0 to 5000) to the circle elements (of which there should be 5000 eventually). So from its point of view, there is no enter'ing data: there are enough circles to hold all your points.
To make sure that the same data point is mapped to the same html element after it changed index in its array, you need to use an id field of some sort attached to each of your data point, and tell d3 to use this id to map the data to elements, instead of their index.
points = svg.selectAll("circle")
.data(dataPoints, function(d){return d.id})
If the coordinates are a good identifier for your point, you can directly use:
points = svg.selectAll("circle")
.data(dataPoints, function(d){return d.longitude+" "+d.latitude})
See https://github.com/mbostock/d3/wiki/Selections#data for more details.
I'm trying to create a basic d3 pie chart with a legend. I'm following the examples in two different tutorials and somehow code from one example isn't playing well with the other. What I'm trying to do is set an ordinal scale's domain so I can use that to create a legend.
On the following line, I set the domain. If I step through the code, I can see that immediately after I get ["HEURISTIC", "ADWARE", "COMPANY_BLACK_LIST", "PUP", "SUSPECTED_MALWARE", "KNOWN_MALWARE"]. This is exactly what I want.
color.domain(labels)
However, if I keep stepping through, once I reach the following line, the domain changes to ["HEURISTIC", "ADWARE", "COMPANY_BLACK_LIST", "PUP", "SUSPECTED_MALWARE", "KNOWN_MALWARE", 0, 1, 2, 3, 4, 5]
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
QUESTION: What is causing those six extra items to be inserted into the domain?
Code (http://jsfiddle.net/tonicboy/2urZY/5/):
var w = 150,
h = 100,
r = 50,
color = d3.scale.category20c(),
dataset = [{"name":"HEURISTIC","value":65},{"name":"ADWARE","value":75},{"name":"COMPANY_BLACK_LIST","value":9},{"name":"PUP","value":34},{"name":"SUSPECTED_MALWARE","value":14},{"name":"KNOWN_MALWARE","value":156}],
labels = _.pluck(dataset, "name");
color.domain(labels);
var chart = d3.select("#pie_chart")
.append("svg:svg")
.data([dataset])
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", "0 0 " + w + " " + h)
.attr("preserveAspectRatio", "xMinYMin meet");
var vis = chart.append("g")
.attr("transform", "translate(" + (w - r) + "," + r + ")");
var arc = d3.svg.arc()
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.value; });
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
var legend = chart.append("g")
.attr("class", "pie-legend")
.selectAll("g")
.data(color.domain())
.enter()
.append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 7 + ")"; });
legend.append("rect")
.attr("width", 5)
.attr("height",5)
.style("fill", color);
legend.append("text")
.attr("x", 8)
.attr("y", 9)
.text(function(d) { return d; });
Here is what the chart looks like so far:
You're setting your ordinal scale domain with strings, but then calling it with index numbers. If you ask an ordinal scale for a value that isn't currently in its domain, it will add it to the domain and assign it the next value in the range (or recycle the range values if it runs out).
Original code:
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
Should be
arcs.append("svg:path")
.attr("fill", function(d, i) {return color( d.data.name); } )
.attr("d", arc);
The d value is the object created by the pie chart function; it stores the original data object as d.data. The name from that data is one of the values used in the color scale domain.
Updated fiddle: http://jsfiddle.net/2urZY/6/
I've used arc.Centroid to try to plot my circles on the arcs with labels. However, the labels do not stay with it?
force.on("tick", function() {
text.attr("x", function(d) { return d.x + 6; })
.attr("y", function(d) { return d.y + 4; });
node.attr("transform", function(d,i) {
return "translate(" + arc[i].centroid(d) + ")"; })
});
I have attempted to put centroid & arc[i] instead of the x & y. How can I put my circles with text? http://jsfiddle.net/xwZjN/20/
Also say if I were to have more json data, would I be able to restrict the plots only going into each section e.g. each section being a category?
Any help would be great. I think the solution may be similar to this - http://jsfiddle.net/nrabinowitz/GQDUS/
It seems that the force layout is not the right choice for your application. Try to group your symbol and text in a g element and place them at the calculated coordinates. See updated fiddle without force layout: http://jsfiddle.net/xwZjN/26/
var node = svg.selectAll("g.node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d,i) {
return "translate(" + arc[i].centroid() + ")";
});
node.append("path")
.attr("d", d3.svg.symbol().type(function(d) { return d.type; }))
// change (0,0) for exact symbol placement
.attr("transform", "translate(0,0)")
.style("fill", "blue" );
node.append("text")
.text(function(d) { return d.Name; })
// shift text in nice position
.attr("x", 10)
.attr("y", 5);
Given a tree diagram like the Dendrogram example (source), how would one put labels on the edges? The JavaScript code to draw the edges looks like the next lines:
var link = vis.selectAll("path.link")
.data(cluster.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
Mike Bostock, the author of D3, very graciously helped with the following solution. Define a style for g.link; I just copied the style for g.node. Then I replaced the "var link =...." code with the following. The x and y functions place the label in the center of the path.
var linkg = vis.selectAll("g.link")
.data(cluster.links(nodes))
.enter().append("g")
.attr("class", "link");
linkg.append("path")
.attr("class", "link")
.attr("d", diagonal);
linkg.append("text")
.attr("x", function(d) { return (d.source.y + d.target.y) / 2; })
.attr("y", function(d) { return (d.source.x + d.target.x) / 2; })
.attr("text-anchor", "middle")
.text(function(d) {
return "edgeLabel";
});
The text function should ideally provide a label specifically for each edge. I populated an object with the names of my edges while preparing my data, so my text function looks like this:
.text(function(d) {
var key = d.source.name + ":" + d.target.name;
return edgeNames[key];
});