0
使用Javascript和d3庫我已製作了英國(不包括NI)的選區地圖,並添加了選擇每個選區顏色的功能。我現在希望計算每種顏色的選區數量並將它們顯示在條形圖上。選區數據來自topojson文件。使用d3計算所選元素
有人可以告訴我如何做到這一點。非常感謝
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
/* define style for map */
.constituency {
fill: black;
stroke: #fff;
stroke-width: 0.25px;
}
// .constituency.W28 { fill: red; }
</style>
</head>
<body>
<div id='map'></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
// create map
var width = 700,
height = 1000;
var projection = d3.geo.albers()
//.center([0, 55.4])
.center([3, 54])
.rotate([4.4, 0])
.parallels([50, 60])
.scale(4000)
.translate([width/2, height/2])
//.translate(200,200)
;
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.behavior.zoom().on('zoom', redraw))
.call(d3.behavior.zoom().on("dblclick.zoom", null)
;
function redraw() {
svg.attr('transform', 'translate(' + d3.event.translate + ') scale(' + d3.event.scale + ')');
}
var currentColor = "black";
var toggleColor = (function(){
var i=0;
var Colors = ["black","rgba(5, 117, 201, 1)", "rgba(237, 30, 14, 1)", "rgba(254, 131, 0, 1)", "rgba(235, 195, 28, 1)", "rgba(113, 47, 135, 1)", "rgba(120, 195, 30, 1)","rgba(78, 159, 47, 1)"];
return function(){
i=0;
if(currentColor != "rgba(120, 195, 30, 1)"){
while(currentColor != Colors[i]){
i++;
}
currentColor = Colors[i+1];
}
else{
currentColor = "black";
}
// currentColor = currentColor == "rgba(5, 117, 201, 1)" ? "rgba(237, 30, 14, 1)" : "rgba(5, 117, 201, 1)";
d3.select(this).style("fill", currentColor);
}
})();
d3.json("constituencies.topo.json", function(error, topology) {
// create a polygon for every constituency
svg.selectAll(".constituency")
// retrieve the features so that we can access the id
.data(topojson.feature(topology, topology.objects.constituencies).features)
.enter().append("path")
.attr("class", function(d) { return "constituency " + d.id; })
.attr("d", path)
.style("fill", "black")
.on("click", toggleColor)
});
</script>
</body>
</html>
非常感謝亞當,我偶然以同樣的方式工作,但感謝您的幫助。我可以請你看看我的另一個問題,繼續這段代碼,我有一個HTML條形圖,列出所有彩色選區的數組,但是在選擇顏色後似乎沒有重新繪製 – Hanros94
請確保你實際上將更新的數據附加到條上。要麼刪除所有現有的欄,並使用.data(byColor).enter()再次添加它們或使用選擇.merge https://bl.ocks.org/mbostock/3808218 –