问题
I am having issues with Choropleth Map using D3.
I want to show occurrences of disaster to the World Map for the given year, say 2015.
I have a dropdown to change disaster type. I am currently working with "Earthquake".
Before selecting "Earthquake" from dropdown:
After Selecting "Earthquake", it is changing colors, but somehow not changing as per the value. Below is the output:
Below is my code to generate map, It is not showing any error as well.
// Load Data
d3.csv("disaster_data.csv", function(data){
// Set color
color.domain([
d3.min(data, function(d) { return +d[occurrence]; }),
d3.max(data, function(d) { return +d[occurrence]; })
]);
// Load Map JSON
d3.json("d3-geo/mapshaper_output.json", function(error, json) {
if (error) throw error;
// Create Map
var countries = svg.selectAll(".countries")
.data(json.features)
.enter()
.append("path");
countries.attr("d", path)
.attr("stroke", "gray");
// Return number of occurrences for given dataset countrywise
function get_occurrences(disaster_type, year){
if(disaster_type == "Earthquake"){
var dataEarthquake = data.filter(function(a) {return a.disaster_type == disaster_type});
var dataEarthquake_Year = dataEarthquake.filter(function(a) {return a.year == year});
for(var i = 0; i < dataEarthquake_Year.length; i++){
var dataCountryCode = dataEarthquake_Year[i].iso;
var dataOccurence = +dataEarthquake_Year[i].occurrence;
for (var j = 0; j < json.features.length; j++) {
var jsonCountryCode = json.features[j].properties.iso_a3;
if (dataCountryCode == jsonCountryCode) {
json.features[j].properties.occurrence = dataOccurence;
break;
}
}
}
countries.attr("d", path)
.attr("stroke", "gray")
.attr("fill", function(d) {
var value = d.properties[occurrence];
if (value) {
return color(value);
} else {
return "#aaa";
}
});
}
}
// Dropdown change event
dropdown.on("change", change);
var selected_year = 2015;
var occurrence_country = 0;
function change(){
if(this.value == "Earthquake"){
occurrence_country = get_occurrences("Earthquake", selected_year);
}
}
}); // JSON ends
d3.select(self.frameElement).style("height", height + "px");
}); // CSV Load ends
Can anyone please look into the code and help?
EDITED: Adding code which used for color
var colorgrad = ['#fcfbfd','#efedf5','#dadaeb','#bcbddc','#9e9ac8','#807dba','#6a51a3','#54278f','#3f007d'];
var color = d3.scale.quantize().range(colorgrad);
回答1:
Instead of:
countries.attr("d", path)
.attr("stroke", "gray")
.attr("fill", function(d) {
var value = d.properties[occurrence];
if (value) {
return color(value);
} else {
return "#aaa";
}
});
Try:
d3.selectAll("path)
.attr("stroke", "gray")
.attr("fill", function(d) {
var value = d.properties[occurrence];
if (value) {
return color(value);
} else {
return "#aaa";
}
});
来源:https://stackoverflow.com/questions/40591970/d3-choropleth-map-colors-are-not-appearing