Need Help Coloring In Countries From An Array, Leave Rest Default Color
Solution 1:
Ok, let's go step by step:
First, we'll grab the value for rank for each country in your data2 and we'll push that value in your GeoJSON, as a new property. Here is the code, that I got from Scott Murray (I see that in your code you use "topo" as a parameter name, but here I'm using "json"):
d3.json("yourgeojsonfile.json", function(json) {
//Merge the rank in data2 and GeoJSON in a single array//Loop through once for each "rank" data valuefor (var i = 0; i < data2.length; i++) {
//Grab country namevar data2CountryCode = data2[i].country_code;
//Grab data value, and convert from string to floatvar dataValue = +data2[i].rank;
//Find the corresponding country inside the GeoJSONfor (var j = 0; j < json.features.length; j++) {
//We'll check the official ISO country codevar jsonCountryCode = json.features[j].properties.iso_a3;
if (data2CountryCode == jsonCountryCode) {
//Copy the data2 rank value into the GeoJSON, with the name "color"
json.features[j].properties.color = dataValue;
//Stop looking through the JSONbreak;
}
}
}
//the rest of your code
});
Check if you have ISOa3 in your Geojson, or any other country code to match country_code in your data2. Now we have a property named "color" in your GeoJSON, that matches "rank" in your data2. The next step is simple:
var country = g.selectAll(".country")
.data(topo.features) //in my example, json.features
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
//Get data valuevar value = d.properties.color;
if (value) {
//If value exists…return color(value);
} else {
//If value is undefined…return"#ccc";
}
});
So, if there is a value for d.properties.color, it will fill according to var color = d3.scale.category10(). If there is no value, it will fill with #ccc, or whatever you want. Just to finish, if you want to fill them from red to green, dont use d3.scale.category10(). Instead, use:
var color = d3.scale.quantize()
.range([ //put your colors here as an array ])
.domain([d3.min(data2, function(d) { return d.rank; }),
d3.max(data2, function(d) { return d.rank; })
]);
For the colors, I recommend Cynthia Brewer's palette:
EDIT: Only after reading the full code I realized that you are using TopoJSON. The code in my solution works for GeoJSON, not TopoJSON.
Solution 2:
You need to use a colour range using a scale, and not using ordinal values. You set the lower colour, the upper colour, and d3 works out where value d is between the min and max values and applies that percentage to work out the colour.
var colorScale = d3.scale.linear()
.range(['lightgreen', 'darkgreen']) // or use hex values
.domain([minValue, maxValue]);
Take a look here: Gradient color in a treemap for D3
Post a Comment for "Need Help Coloring In Countries From An Array, Leave Rest Default Color"