Подсчет выбранных элементов с помощью d3

Используя Javascript и библиотеку d3, я составил карту избирательных округов в Великобритании (исключая NI) и добавил возможность выбирать цвет каждого избирательного округа. Теперь я надеюсь подсчитать количество избирательных округов каждого цвета и отобразить их на гистограмме. Данные избирательных округов поступают из файла топойсона.

Может ли кто-нибудь посоветовать мне, как это сделать. Большое спасибо

<!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>

1 ответ

Сохраните ссылку на группы, которые вы создали с помощью topojson:

var constituencies = topojson.feature(topology, topology.objects.constituencies).features
svg.selectAll(".constituency")
    .data(constituencies).features)
    .enter().append("path")
...

Затем настройте функцию click, чтобы обновить DOM и группу, привязанную к этому элементу, с текущим цветом:

return function(d){
  i = 0;
  if (currentColor != "rgba(120, 195, 30, 1)"){
    while(currentColor != Colors[i]) i++;
    currentColor = Colors[i+1];
  } else{ currentColor  = "black"; }

  d3.select(this).style("fill", currentColor);
  d.currentColor = currentColor; // save currentColor
}

Теперь вы можете группировать группы по цвету и использовать эту информацию для гистограммы:

 var byColor = d3.nest().key(d => d.currentColor).entries(constituencies)
Другие вопросы по тегам