簡體   English   中英

如何在d3.js(albersUsa)中為每個州添加Label?

[英]How to add Label to each state in d3.js (albersUsa)?

us.json加載,但是當我嘗試添加Label名稱時,我無法使其工作。 我沒有在.json文件中看到name屬性,所以如何添加每個州名? 我對這個框架很陌生。

我在Google和Stackoverflow上嘗試了不同的教程,但它們都不適合我。 這是我試過的情侶教程的鏈接,我認為值得。

我擔心的問題:

  1. 我想我在us.json文件中缺少name屬性。 (如果這是問題,是否有任何其他.json文件包含州名?如何使用該文件的州名?)
  2. 美國州名是否包括在http://d3js.org/topojson.v1.min.js

.html文件(框架已加載)

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>

.js文件:

var width = 1500,
    height = 1100,
    centered;


var usData = ["json/us.json"];
var usDataText = ["json/us-states.json"];

var projection = d3.geo.albersUsa()
    .scale(2000)
    .translate([760, height / 2]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .style("width", "100%")
    .style("height", "100%");


svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);

var g = svg.append("g");

d3.json(usData, function(unitedState) {
  g.append("g")
    .attr("class", "states-bundle")
    .selectAll("path")
    .data(topojson.feature(unitedState, unitedState.objects.states).features)
    .enter()
    .append("path")
    .attr("d", path)
    .attr("class", "states")
    .on("click", clicked);
});

先謝謝大家。 如果你告訴我你在哪里學習d3.js我也很感激。

如你所說,你的us.json中沒有州名。 然而,它擁有獨特的ID,幸運的是,Bostock先生已將這些ID映射到這里

所以,讓我們稍微修改一下這段代碼。

首先,使json請求拉取數據:

// path data
d3.json("us.json", function(unitedState) {
  var data = topojson.feature(unitedState, unitedState.objects.states).features;
  // our names
  d3.tsv("us-state-names.tsv", function(tsv){
    // extract just the names and Ids
    var names = {};
    tsv.forEach(function(d,i){
      names[d.id] = d.name;
    });

現在添加我們的可視化

// build paths
g.append("g")
  .attr("class", "states-bundle")
  .selectAll("path")
  .data(data)
  .enter()
  .append("path")
  .attr("d", path)
  .attr("stroke", "white")
  .attr("class", "states");

 // add state names
 g.append("g")
  .attr("class", "states-names")
  .selectAll("text")
  .data(data)
  .enter()
  .append("svg:text")
  .text(function(d){
    return names[d.id];
  })
  .attr("x", function(d){
      return path.centroid(d)[0];
  })
  .attr("y", function(d){
      return  path.centroid(d)[1];
  })
  .attr("text-anchor","middle")
  .attr('fill', 'white');

  ....

這是一個有效的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM