正如我的用戶名所示,我正在學習d3.js,使用Scott Murray的優秀書籍。作爲一項練習,我試圖用一些關於美國輟學率的公開數據創建一個choropleth(與他在書中使用的非常相似)。我有兩個單獨的csvs,一個是來自一組學生的數據,另一個是不同組的數據。我希望數據可以通過單擊從一個CSV更新到另一個的數據。除了數值名稱(DRPHI vs DRPBL),csvs的名稱和值本身,它們是相同的。但是,點擊更新無效 - 沒有任何反應。 我在這裏錯過了一些非常基本的東西嗎?我很抱歉,如果我。非常感謝您的參與。 我的代碼(基於非常倚重穆雷的代碼)是在這裏:d3.js - 基於新的.csv更新choropleth中的數據?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Setting path fills dynamically to generate a choropleth</title>
<script type="text/javascript" src="../d3/d3.v3.js"></script>
<style type="text/css">
</style>
</head>
<body>
<p>Click on this text to update the chart with values for another set of students.</p>
<script type="text/javascript">
var w = 500;
var h = 300;
var projection = d3.geo.albersUsa()
.translate([w/2, h/2])
.scale([500]);
var path = d3.geo.path()
.projection(projection);
var color = d3.scale.quantize()
.range(["rgb(237,248,233)","rgb(186,228,179)","rgb(116,196,118)","rgb(49,163,84)","rgb(0,109,44)"]);
//Colors taken from colorbrewer.js, included in the D3 download
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
d3.csv("1_dropout_by_state.csv", function(data) {
color.domain([
d3.min(data, function(d) { return d.DRPHI; }),
d3.max(data, function(d) { return d.DRPHI; })
]);
d3.json("us-states.json", function(json) {
for (var i = 0; i < data.length; i++) {
var dataState = data[i].state;
var dataValue = parseFloat(data[i].DRPHI);
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.name;
if (dataState == jsonState) {
json.features[j].properties.value = dataValue;
break;
}
}
}
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return "#ccc";
}
});
});
});
d3.select("p")
.on("click", function() {
d3.csv("2_dropout_by_state.csv", function(data) {
color.domain([
d3.min(data, function(d) { return d.DRPBL; }),
d3.max(data, function(d) { return d.DRPBL; })
]);
d3.json("us-states.json", function(json) {
for (var i = 0; i < data.length; i++) {
var dataState = data[i].state;
var dataValue = parseFloat(data[i].DRPBL);
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.name;
if (dataState == jsonState) {
json.features[j].properties.value = dataValue;
break;
}
}
}
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return "#ccc";
}
});
});
});
});
</script>
</body>
</html>