javascript - D3.js 使用 csv 文件中的数据填充 svg map

标签 javascript csv svg d3.js

我有一个 svg map ,每个路径都有一个 class="county-code-###"。

还有一个包含县名称、县代码和县人口的 csv 文件。

我已启动以下操作,但不确定如何使用来自 csv 的日期填充正确的路径。

    d3.text("counties.csv", function (datasetText) {

        var parsedCSV = d3.csv.parseRows(datasetText);

        var sampleHTML = d3.select("div")
            .append("div")
            .style("")
            .style("")

        .selectAll("path")
            .data(parsedCSV)
            .enter().append("path")

    });

最佳答案

您可以使用datum方法将区域名称(和 ID)添加到数据中。像这样的东西:

<script>
  var height = 500;
  var width = 700;

  // generate a sample 'map'. This svg does not contain the names of the 
  // regions
  var data = [{id:1, x:10, y:10}, {id:2, x:300, y:400}, {id:3, x:600, y:100}];
  var vis = d3.select("#vis").append("svg")
    .attr("width", width).attr("height", height);
  vis.selectAll("rect").data(data).enter().append("rect")
    .attr("x", function(d) { return d.x;})
    .attr("y", function(d) { return d.y;})
    .attr("width", 20).attr("height", 20)
    .attr("class", function(d) { return "county-code-" + d.id;});

  // Some sample data containing the region names; in this case hard coded, 
  // but could also be read from a csv file. 
  var data2 = [{id:1, name:"a"}, {id:2, name:"b"}, {id:3, name:"c"}];

  // Add the names to the svg
  vis.selectAll("rect").datum(function(d) {
    // extract county code from class
    var id = +d3.select(this).attr("class").match(/county-code-(\d+)/)[1];
    d.id = id;
    // look up id in data2; if found add name to datum
    for (var i = 0; i < data2.length; i++) {
      if (data2[i].id == id) {
        d.name = data2[i].name;
        break;
      }
    }
    return d;
  });


</script>

关于javascript - D3.js 使用 csv 文件中的数据填充 svg map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24731729/

相关文章:

python - 将 CSV 转换为 numpy

python csv到字典列

javascript - 使用 HTML5 放大国家/地区的世界地图

javascript - 如何在 ionic 应用程序中共享链接回应用程序的链接

regex - 使用 Linux shell 命令从 CSV 文件中提取列

javascript - setTimeout 函数意外行为

css - 如何防止 SVG 进入另一个 SVG 剪辑

javascript - 强制从分配的 SVG 大小绘制有向图

javascript - 以编程方式打开 Vuetify 中的每个扩展面板

javascript - 如何使用 javascript 在长字符串中查找 block 并替换